Laravel 4.2加入Table和分页

Laravel 4.2 Join Table and Pagination

我学习 Laravel 4.2 并尝试使用连接 table 和分页。 使用分页时我的代码有效。但是当我与 join table 结合使用时,它不起作用。

这是我的控制器: BookController.php

public function index()
    {
        // Get All Books
        //$booksList = Book::all();
        $booksList = Book::with('category')->paginate(2);

        return View::make('books.index', compact('booksList'));
    }

我得到这样的错误:

Call to undefined method Illuminate\Database\Query\Builder::category()

我的类别模型就像这样:

<?php 
    class Category extends Eloquent
    {

    }

我的图书模型是这样的:

<?php 
    class Book extends Eloquent
    {
        protected $fillable = array('isbn', 'title', 'author', 'publisher', 'language');
    }

并且在index.blade.php中:

<tr>
            <td>{{ $book->id }}</td>
            <td>{{ $book->isbn }}</td>
            <td>{{ $book->category_id }}</td>
            <td>{{ $book->title }}</td>
            <td>{{ $book->author }}</td>
            <td>{{ $book->publisher }}</td>
            <td>@if ($book->language == 1) {{ 'English' }} @else {{ 'Indonesian' }} @endif</td>
            <td>
                {{ link_to_route('books.show', 'Read', array($book->id), array('class' => 'btn btn-primary btn-xs')) }}
            </td>
            <td>
                {{ link_to_route('books.edit', 'Edit', array($book->id), array('class'=>'btn btn-warning btn-xs')) }}
            </td>
            <td>
                {{ Form::open(array('method'=>'DELETE', 'route'=>array('books.destroy', $book->id))) }}
                {{ Form::submit('Delete', array('class'=>'btn btn-danger btn-xs', 'onclick' => 'return confirm("Are you sure?")')) }}

                {{ Form::close() }}
            </td>
        </tr>

我的 Table 结构如下:

请帮忙谢谢

with('category') 并不意味着加入,而是 eager loading

它实际上会执行连接以预先加载您的数据但是您必须为模型定义关系,以便laravel了解要做什么。

简而言之,您只能在现有模型关系上使用 with()。在您的情况下,您应该按如下方式更改模型:

类别

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

图书

class Book extends Eloquent
{
  protected $fillable = array('isbn', 'title', 'author', 'publisher', 'language');

  public function category(){ 
    return $this->belongsTo('Category');
  }
}

更多关于 Laravel Relationships

当您在 eloquent 中使用连接时,您必须像这样在模型中实现关系:

<?php 
class Book extends Eloquent
{
    protected $fillable = array('isbn', 'title', 'author', 'publisher', 'language');

     public function category(){
        return $this->belongsTo('Category');
     }

}

<?php 
class Category extends Eloquent
{
    public function book(){
        return $this->hasMany('Category');
     }
}