Laravel Eloquent'属于'关系书及其类别

时间:2015-01-23 16:20:28

标签: php laravel-4 eloquent

我正在尝试在“书籍”表格中打印所有书籍的名称及其相关类别。但它没有显示任何内容或错误消息。

型号:: 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

表::书籍

  

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

表:: book_categories

  

(int)id,(string)category

1 个答案:

答案 0 :(得分:1)

将关系添加到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();