LoginSignup
15
10

More than 3 years have passed since last update.

Laravel で updateOrCreate を使う際に Unknown column 'id' in 'where clause' でハマった

Last updated at Posted at 2019-07-19

概要

Laravel の Eloquent が持っている updateOrCreate という関数を使った。
https://readouble.com/laravel/5.7/ja/eloquent.html

MySQL でも気軽に Upsert 処理ができて便利だと思った。

実装例
App\VeryGoodSystem::updateOrCreate(
['user_id' => 12345],
['is_registered' => true]
);

いざ利用してみたところ、下記のようなエラーが出た。
Unknown column 'id' in 'where clause' ...

エラーを追うと、 updateOrCreate で実行されている SQL 文に where `id` is null という条件が付いていることがわかった。

コードを見ても、 id という変数を使っている所は無く、途方に暮れながら調べていたら、良い Q&A を見つけた。(最下部、参考サイト)

つまり、 model に primaryKey が設定されていないと default で id という文字列を使って updateOrCreate 用の SQL を作成してしまうようだった。

利用している Model に $primaryKey = 'user_id' の一行を追加することで解決した。

参考サイト

15
10
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
15
10