firstOrCreate
firstOrCreate 方法將會使用指定的字段 => 值對,來嘗試尋找數據庫中的記錄。如果在數據庫中找不到,5.5
以下版本會使用屬性來添加一條記錄,5.5
及以上版本則將使用第一個參數中的屬性以及可選的第二個參數中的屬性插入記錄
用法:
1
2 |
User::firstOrCreate(['name' => 'Lisi']); User::firstOrCreate(['name' => 'Lisi'], ['age' => 20]); // 5.5及以上版本支持 |
查看源碼:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# 小於 5.5 版本,只有一個參數 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
方法來保存它
用法:
1
2 |
User::firstOrNew(['name' => 'Lisi']); User::firstOrNew(['name' => 'Lisi'], ['age' => 20]); // 5.5及以上版本支持 |
查看源碼:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# 小於 5.5 版本,只有一個參數 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
,此函數版本之間變化不大
用法:
1
|
User::updateOrCreate(['name' => 'Lisi'], ['age' => 20]); |
查看源碼:
1
2 3 4 5 6 7 |
# 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:更新數據,如果不存在則創建