版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010324331/article/details/82698211
updateOrCreate()
和updateOrInsert()
两个方法都是用来保存数据的时候方便操作“ 存在即更新,反之则创建 ”的
updateOrCreate
方法使用的是Eloquent ORM
操作的数据库(支持自动添加创建和更新时间),updateOrInsert
方法使用的是查询构造器(不可以自动添加创建和更新时间)
updateOrCreate
返回值是\Illuminate\Database\Eloquent\Model
,updateOrInsert
返回的是bool
。可以看两个方法的源码注释部分的@return
下面是
updateOrCreate
文档说明和源码
// 如果有从奥克兰到圣地亚哥的航班则将价格设置为 $99
// 如果没有匹配的模型则创建之
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
updateOrCreate
源码部分:
// 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();
});
}
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);
}