我正在尝试打印出“books”表和“book_categories”表中的所有书名及其相关类别。
但是我收到了这个错误:
Trying to get property of non-object (View: books.blade.php)
我的两个表模型的名称:
- Book.php
- BookCategory.php
我的'books'表结构:
id(int), book_name(string), book_category_id(int)
我的“book_categories”表结构:
id(int), book_category(string)
Controller :
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
只要这行代码就可以正确打印出JSON信息:BookCategory::find($book-id)
但是当我使用
->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
关于php - Laravel 4 - 打印表格及其相关类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102837/