找不到列 laravel 5.4

Column not found laravel 5.4

我收到以下错误:

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

当我将 id 值作为 id 传递时。我的数据库中有列名 bookID 但在上面的错误中它正在比较 books.id = 98745632564。我无法理解 book.id 来自哪里。

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

当我按如下方式通过查询传递 id 值时,代码工作正常

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

你应该设置:

protected $primaryKey = 'bookID';

在您的 Book 模型中制作:

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

版本工作。

方法 findfindOrFail 使用主键,默认设置为 id,因此如果您有任何自定义主键,您应该在 Eloquent型号。