0
0

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 1 year has passed since last update.

「Column not found」はモデルでのタイポを疑ってみる

Posted at

はじめに

DM機能実装にあたり、「多対多」のリレーションをモデルファイル上で構築していたところ、「Column not found」というエラーが出ました。

自分の場合、モデル(User.php)内の記述にタイポが存在したのが原因でした。

環境

Laravel 9.52.16

問題

MySQL
> $user->message_rooms()->get();

   Illuminate\Database\QueryException  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'message_room_user.messsage_room_id' in 'field list' (SQL: select `message_rooms`.*, `message_room_user`.`user_id` as `pivot_user_id`, `message_room_user`.`messsage_room_id` as `pivot_messsage_room_id`, `message_room_user`.`created_at` as `pivot_created_at`, `message_room_user`.`updated_at` as `pivot_updated_at` from `message_rooms` inner join `message_room_user` on `message_rooms`.`id` = `message_room_user`.`messsage_room_id` where `message_room_user`.`user_id` = 3).

UserモデルとMessageRoomモデルの多対多のリレーションを確認しようとすると、このようなエラーが出る。

解決策

  • モデル内のリレーション記述にタイポがあったので、それを修正する
User.php(失敗例)
public function message_rooms()
    {
        return $this->belongsToMany(MessageRoom::class, 'message_room_user', 'user_id', 'messsage_room_id')->withTimestamps();
        // "messsage_room_id"になっている
    }
User.php(解決例)
public function message_rooms()
    {
        return $this->belongsToMany(MessageRoom::class, 'message_room_user', 'user_id', 'message_room_id')->withTimestamps();
    }

まとめ

スペルミスなどのタイポによるエラーは、体感エラー箇所の特定が難しい気もします。

そもそも打ち間違えなければ良いだけの話…

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?