Laravel 4 - 打印出 table 及其关联的类别

Laravel 4 - Print out a table and its associated categories

我正在尝试打印 'books' table 和 'book_categories' table 中的所有书名及其相关类别。

但是我收到这个错误:

Trying to get property of non-object (View: books.blade.php)

我的两个table模特的名字:

  • Book.php
  • BookCategory.php

我的'books'table结构:

id(int), book_name(string), book_category_id(int)

我的'book_categories'table结构:

id(int), book_category(string)

控制器:

public function getBooks(){

  $books = Book::all();

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

books.blade.php

@foreach ($books as $book)
<p>{{ $book->book_name }} </p>
<p>{{ BookCategory::find($book->id)->book_category }}</p>
@endforeach

只要这行代码BookCategory::find($book-id)

就可以正确打印出JSON信息

但是当我使用

->first()

->book_category

无法访问其内容。

class Books extends \Model {

    $table = 'books';

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

class BookCategory extends \Model {

    $table = 'book_categories';

    public function books()
    {
        return $this->hasMany('Books', 'book_category_id');
    }
}

public function getBooks() 
{
    // Always eagerload your relation to prevent n+1 issue
    $books = Books::with('categories')->all();

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

@foreach($books as $book)
    {{ $book->book_name}}
    {{ $book->categories->book_category }}
@endforeach

进一步阅读:

http://laravel.com/docs/4.2/eloquent#querying-relations http://daylerees.com/codebright/eloquent-relationships