插入一个新的logging,如果不存在,更新如果存在,laravel雄辩

如果不存在,我们是否有速记插入新logging,如果存在则更新logging? 以下是我使用的代码。

$shopOwner = ShopMeta::where('shopId', '=', $theID)->where('metadataKey', '=', 2001)->first(); if ($shopOwner==null){ insert new record into database } else { update the existing record } 

谢谢

以下是“lu cip”正在谈论的完整示例:

 $user = User::firstOrNew(array('name' => Input::get('name'))); $user->foo = Input::get('foo'); $user->save(); 

这里的文档: http : //laravel.com/docs/eloquent#insert-update-delete

更新:2014年8月27日 – [ updateOrCreate内置到核心…]

为了防止人们仍然遇到这个问题,我写了几个星期后发现,这实际上是Laravel的雄辩的核心的一部分。

挖掘雄辩的等效方法。 你可以在这里看到:

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L553

在:570和:553

  /** * Create or update a record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @return static */ public static function updateOrCreate(array $attributes, array $values = array()) { $instance = static::firstOrNew($attributes); $instance->fill($values)->save(); return $instance; } 

老答案在下面


我想知道是否有任何内置的L4function,以这样做的某种方式,如:

 $row = DB::table('table')->where('id', '=', $id)->first(); // Fancy field => data assignments here $row->save(); 

几个星期前我确实创build了这个方法

 // Within a Model extends Eloquent public static function createOrUpdate($formatted_array) { $row = Model::find($formatted_array['id']); if ($row === null) { Model::create($formatted_array); Session::flash('footer_message', "CREATED"); } else { $row->update($formatted_array); Session::flash('footer_message', "EXISITING"); } $affected_row = Model::find($formatted_array['id']); return $affected_row; } 

我希望有所帮助。 如果有人分享,我很乐意看到这个替代scheme。 @erikthedev_

正如Laravel> = 5.3 ,如果有人仍然好奇如何以简单的方式这样做。 它可能通过使用: updateOrCreate()

例如对于被问到的问题,你可以使用类似于:

 $matchThese = array('shopId'=>$theID,'metadataKey'=>2001); ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']); 

上面的代码将检查由ShopMeta表示的表,这将是最有可能的shop_metas除非在模型本身中没有另外定义

它会尝试find入口

shopId = $theID

metadateKey = 2001

如果发现它会将发现行的列shopOwner更新为New One

如果它find多于一个匹配的行,那么它将更新第一行,这意味着具有最低的主id

如果没有find,那么它会插入一个新的行:

shopId = $theIDmetadateKey = 2001shopOwner = New One

注意检查你的模型是否为$fillable并让你有你想要插入或更新的每个列名,并且其余的列有默认值或者id列自动增加一个。

否则在执行上面的例子时会抛出错误:

 Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))' 

因为在插入新行时将会有一些字段需要值,因此在$fillable没有定义它或者它没有默认值。

有关更多参考资料,请参阅https://laravel.com/docs/5.3/eloquent上的; Laravel文档

从那里的一个例子是:

 // If there's a flight from Oakland to San Diego, set the price to $99. // If no matching model exists, create one. $flight = App\Flight::updateOrCreate( ['departure' => 'Oakland', 'destination' => 'San Diego'], ['price' => 99] ); 

这几乎清除了一切。

我希望它有帮助

保存function:

 $shopOwner->save() 

已经做了你想要的…

Laravel代码:

  // If the model already exists in the database we can just update our record // that is already in this database using the current IDs in this "where" // clause to only update this model. Otherwise, we'll just insert them. if ($this->exists) { $saved = $this->performUpdate($query); } // If the model is brand new, we'll insert it into our database and set the // ID attribute on the model to the value of the newly inserted row's ID // which is typically an auto-increment value managed by the database. else { $saved = $this->performInsert($query); } 
 $shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001)); 

然后进行更改并保存。 注意firstOrNew不会执行插入,如果它没有find,如果你确实需要那么它的firstOrCreate。

实际上,如果寄存器已经存在于数据库中,那么firstOrCreate将不会更新 。 我改进了一点埃里克的解决scheme,因为我实际上需要更新一个具有唯一值的表,不仅为列“ID”

 /** * If the register exists in the table, it updates it. * Otherwise it creates it * @param array $data Data to Insert/Update * @param array $keys Keys to check for in the table * @return Object */ static function createOrUpdate($data, $keys) { $record = self::where($keys)->first(); if (is_null($record)) { return self::create($data); } else { return self::where($keys)->update($data); } } 

那么你会这样使用它:

 Model::createOrUpdate( array( 'id_a' => 1, 'foo' => 'bar' ), array( 'id_a' => 1 ) ); 

就像@JuanchoRamone在上面发布的(感谢@Juancho)对我来说非常有用,但是如果你的数据是数组,你应该修改一下这个:

 public static function createOrUpdate($data, $keys) { $record = self::where($keys)->first(); if (is_null($record)) { return self::create($data); } else { return $record->update($data); } } 

如果您的ID不是自动增量,并且您知道要插入/更新哪一个选项,还有一个选项:

 $object = MyModel::findOrNew($id); //assign attributes to update... $object->save(); 

检查用户是否存在。 如果不插入

 $exist = DB::table('User')->where(['username'=>$username,'password'=>$password])->get(); if(count($exist) >0) { echo "User already exist";; } else { $data=array('username'=>$username,'password'=>$password); DB::table('User')->insert($data); } Laravel 5.4