Laravel Eloquent 'belongs to' 关系书籍及其类别

Laravel Eloquent 'belongs to' relationship books and its category

我正在尝试打印 'books' table 中所有书籍的名称及其关联的类别。但它不显示任何内容或错误消息。

型号::Book.php

class Book extends Eloquent{
    protected $table ='books';

    public function bookCat()
    {
        return $this->belongsTo('BookCategory');
    }
}

型号::BookCategory.php

class BookCategory extends Eloquent{
    protected $table ='book_categories';

}

控制器::route.php

Route::get('/', function()
{
    $books = Book::all();

    return View::make('books')
    ->with('books', $books);
});

视图::books.blade.php

@foreach ($books as $book)

<li>{{ $book->book_name }}</li>
- <small>{{ $book->bookCat }}</small>

@endforeach

Table::书籍

(int)id, (string)book_name, (int)category_id

Table::book_categories

(int)id, (string)category

将关系添加到 BookCategory。

class BookCategory extends Eloquent{
    protected $table ='book_categories';

    public function books() {
        return $this->hasMany('Book');
    }
}

您的本地密钥也不匹配模型名称,因此您需要在关系中指定:

class Book extends Eloquent{
    protected $table ='books';

    public function bookCat()
    {
        return $this->belongsTo('BookCategory', 'category_id');
    }
}

您可能还想预先加载控制器中的类别,因为您查询的是书籍:

$books = Book::with('bookCat')->get();