Laravel 4 - 打印表格及其相关类别

时间:2015-01-23 04:03:31

标签: php mysql laravel blade

我试图在“书籍”中打印出所有书籍名称及其相关类别。表和' book_categories'表。

但是我收到了这个错误:

  

尝试获取非对象的属性(查看:books.blade.php)

我的两个表格模型的名称:

  
      
  • book.php中
  •   
  • BookCategory.php
  •   

我的书'表结构:

  

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

我的书#categories'表结构:

  

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

只有这行代码才能正确打印出JSON信息:BookCategory::find($book-id)

但是当我使用

  

- &gt;首先()

  

- &GT; book_category

要访问其内容,它无效。

1 个答案:

答案 0 :(得分:1)

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