laravel updateOrCreate 和 updateOrInsert 的区别
updateOrCreate() 和 updateOrInsert() 两个方法都是用来保存数据的时候方便操作“ 存在即更新,反之则创建 ”的
updateOrCreate 方法使用的是 Eloquent ORM 操作的数据库(支持自动添加创建和更新时间) –有时候我们需要判断某条数据是否存在,如果存在更新,否则插入,那可能你需要updateOrCreate
updateOrInsert 方法使用的是查询构造器(不可以自动添加创建和更新时间)
updateOrCreate 返回值是\Illuminate\Database\Eloquent\Model, updateOrInsert 返回的是 bool。可以看两个方法的源码注释部分的 @return
下面是updateOrCreate文档说明和源码
updateOrCreate 源码部分:
// 如果有从奥克兰到圣地亚哥的航班则将价格设置为 $99
// 如果没有匹配的模型则创建之
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
// namespace Illuminate\Database\Eloquent;
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values)->save();
});
}
参数$attributes是where条件,根据attributes参数去数据库匹配是否有相关数据,如果没有则新建数据,有就查询出来
然后在fill参数values的值去保存
$create_bool = Logistics::updateOrCreate([
'id' => $model['id'],
],[
'a' => $model['a'],
'a' => $model['b'],
'a' => $model['c'],
'a' => $model['d'],
]);
updateOrInsert 源码部分:
// namespace Illuminate\Database\Query
/**
* Insert or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return bool
*/
public function updateOrInsert(array $attributes, array $values = [])
{
if (! $this->where($attributes)->exists()) {
return $this->insert(array_merge($attributes, $values));
}
return (bool) $this->take(1)->update($values);
}