firstOrCreateとは
firstOrCreateメソッドは指定されたカラム/値ペアでデータベースレコードを見つけようします。
モデルがデータベースで見つからない場合は、最初の引数が表す属性、任意の第2引数があればそれが表す属性も同時に含む、レコードが挿入されます。
以下のように実装した場合
User::query()->where('uuid', '=', $uuid)->firstOrCreate([
'uuid' => $uuid,
'type' => $type,
'event' => $event,
]);
以下のようなSQLが発行される
select * from `users`
where `uuid` = ? and (`uuid` = ? and `type` = ? and `event` = ?)
limit 1
insert into `users` (`uuid`, `type`, `event`) values (?, ?, ?)
select文が…!
Laravel側のソースを見てみると、引数を全てWhere句に突っ込んでるんですね。
/**
* Get the first record matching the attributes or create it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrCreate(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return tap($this->newModelInstance($attributes + $values), function ($instance) {
$instance->save();
});
}
ドキュメントを言葉通りに受け止めましょうという話
firstOrCreateメソッドは指定されたカラム/値ペアでデータベースレコードを見つけようします。