4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Laravel5.6】firstOrCreateの罠

Last updated at Posted at 2019-09-03

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メソッドは指定されたカラム/値ペアでデータベースレコードを見つけようします。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?