gpt4 book ai didi

php - Laravel 4.2 连接表和分页

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:00 25 4
gpt4 key购买 nike

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

这是我的 Controller :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>

我的表结构是这样的: enter image description here

enter image description here

请帮忙谢谢

最佳答案

当你在 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');
}
}

关于php - Laravel 4.2 连接表和分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31197673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com