Column not found laravel 5.4

此生再无相见时 提交于 2019-12-11 06:03:36

问题


I get the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'books.id' in 'where clause' (SQL: select * from books where books.id = 98745632564 limit 1)

when I pass id value as id. I have column name bookID in my database but in the above error it is comparing books.id = 98745632564. I could not understand where book.id is coming from.

public function showBook($id){
   $book = Book::findOrFail($id);
   return $book;
}

The code works perfectly fine when I pass id value with the query as follows

public function showBook($id){
    $book = Book::where('bookID', $id)->find();
    return $book;
}

回答1:


You should set:

protected $primaryKey = 'bookID';

in your Book model to make:

$book = Book::findOrFail($id);

version work.

Methods find or findOrFail are using primary key and this is by default set to id, so if you have any custom primary key, you should set it in your Eloquent model.



来源:https://stackoverflow.com/questions/43478429/column-not-found-laravel-5-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!