firstOrCreate、firstOrNew、updateOrCreate 方法使用
阿新 • • 發佈:2019-01-11
在日常開發的過程中,經常會遇到判斷一條記錄是否存在、存在更新、不存在新建記錄這種場景,在 Laravel
中提供了方法支援,那麼下面就看下具體的方法;
firstOrCreate
firstOrCreate 方法將會使用指定的欄位 => 值對,來嘗試尋找資料庫中的記錄。如果在資料庫中找不到,5.3
以下版本會使用屬性來新增一條記錄,5.3
及以上版本則將使用第一個引數中的屬性以及可選的第二個引數中的屬性插入記錄
用法:
User::firstOrCreate(['name' => 'Lisi']); User::firstOrCreate(['name' => 'Lisi'], ['age' => 20]); // 5.3及以上版本支援
原始碼:
# 小於 5.3 版本,只有一個引數 public function firstOrCreate(array $attributes) { if (! is_null($instance = $this->where($attributes)->first())) { return $instance; } $instance = $this->model->newInstance($attributes); $instance->save(); return $instance; } # 5.5 版本 public function firstOrCreate(array $attributes, array $values = []) { // 判斷是否存在,如果存在,返回例項 if (! is_null($instance = $this->where($attributes)->first())) { return $instance; } // 不存在建立,此程式碼簡化就是 $this->newModelInstance($attributes + $values)->save(); return tap($this->newModelInstance($attributes + $values), function ($instance) { $instance->save(); }); }
firstOrNew
會嘗試使用指定的屬性在資料庫中尋找符合的紀錄。如果未被找到,將會返回一個新的模型例項。請注意 firstOrnew
返回的模型還尚未儲存到資料庫。你需要通過手動呼叫 save
方法來儲存它
用法:
User::firstOrNew(['name' => 'Lisi']); // 5.4 以下版本
User::firstOrNew(['name' => 'Lisi'], ['age' => 20]); // 5.4及以上版本支援
原始碼:
# 小於 5.4 版本,只有一個引數 public function firstOrNew(array $attributes) { if (! is_null($instance = $this->where($attributes)->first())) { return $instance; } return $this->model->newInstance($attributes); } # 5.5 版本 public function firstOrNew(array $attributes, array $values = []) { if (! is_null($instance = $this->where($attributes)->first())) { return $instance; } return $this->newModelInstance($attributes + $values); }
檢視原始碼就更清楚 firstOrCreate
比 firstOrNew
多了 save
方法,兩個方法都很實用,根據場景使用它。
UpdateOrCreate
更新資料,如果不存在則建立,這個函式就充分利用到了方法 firstOrNew
,此函式版本之間變化不大
用法:
User::updateOrCreate(['name' => 'Lisi'], ['age' => 20]);
原始碼:
# 5.5 版本
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values)->save();
});
}
總結:
firstOrCreate:判斷之後直接入庫
firstOrNew:判斷之後還要做其他業務流程,之後再入庫
updateOrCreate:更新資料,如果不存在則建立