【问题标题】:Laravel 4.2 Join Table and PaginationLaravel 4.2 连接表和分页
【发布时间】:2015-09-20 18:09:00
【问题描述】:

我学习 Laravel 4.2 并尝试使用连接表和分页。 我的代码在使用分页时工作。但是当我结合连接表时它不起作用。

这是我的控制器: 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>

我的表结构是这样的:

请帮忙谢谢。

【问题讨论】:

  • 能否提供您的 Book 模型的代码?
  • @JSelser 我已经添加了,谢谢:)

标签: php mysql laravel-4 pagination


【解决方案1】:

with('category') 不代表加入,而是渴望加载

它实际上会执行连接以预先加载您的数据但是您必须为模型定义关系才能让 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

【讨论】:

    【解决方案2】:

    当你在 eloquent 中使用 join 时,你必须像这样实现与模型的关系:

    <?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');
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2016-06-14
      • 2023-03-24
      • 2023-03-16
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      相关资源
      最近更新 更多