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();
});
}