如何在laravel中对相关模型进行分页
Posted
技术标签:
【中文标题】如何在laravel中对相关模型进行分页【英文标题】:How to paginate a related model in laravel 【发布时间】:2015-08-10 14:39:35 【问题描述】:我有两个模型,即 RoomCategory 和 Room。我想通过foreach循环对每个房间类别相关的所有房间进行分页,这是我的MVC。
型号
class RoomCategory extends \Eloquent
public function Room()
return $this->hasMany('Room','category_id','id','RoomCategory');
class Room extends \Eloquent
public function RoomCategory()
return $this->belongsTo('RoomCategory','id','category_id','Room');
控制器
public function index()
$room_category = RoomCategory::get()
->with('Room')->paginate(1);
return View::make('pages.roomlist', compact('room_category'));
查看
@foreach($room_category as $category)
$category->name
@foreach($category->room as $rooms)
$rooms->name
$category->room->links()
@endforeach
@endforeach
我得到了这个错误
调用未定义的方法 Illuminate\Database\Eloquent\Collection::with()
有人可以帮助我如何在房间类别的 foreach 循环下对这些房间进行分页。谢谢
【问题讨论】:
【参考方案1】:如果您使用分页,则不需要 get() 方法。替换这个
$room_category = RoomCategory::get()
->with('Room')->paginate(1);
有了这个
$room_category = RoomCategory::with('Room')->paginate(1);
编辑
最好不要在索引页面中使用分页链接来表示房间,只需对房间类别进行分页即可。
$room_category = RoomCategory::with([
'Room' => function($query)
$query->latest()->limit(5);
])->paginate(3);
在您的索引视图上对类别进行分页,并为每个类别页面建立一个链接并将您的房间分页
index.blade.php
@foreach($room_category as $room_cat)
@foreach($room_cat->Room as $room)
<div class="room-section"></div>
@endforeach
<a href=" url('category', $room_cat->id) ">View more of this category</a>
@endforeach
$room_category->links()
你的控制器
public function showCategory($id)
$room_category = RoomCategory::with([
'Room' => function($query)
$query->latest()->paginate(8);
])->find($id);
return View::make('category.show', compact('$room_category'));
和category/show.blade.php你可以对房间进行分页
@foreach($room_category->Room as $room)
<div class="room-section"></div>
@endforeach
$room_category->Room()->links()
【讨论】:
在我执行此代码时再次出错Call to undefined method Illuminate\Database\Eloquent\Collection::links()
它分页 $room_category 而不是 $category->room【参考方案2】:
要实现您想要的,您必须获取所有房间类别,遍历它们,然后遍历每个房间类别房间。
这是示例代码:
public function index()
$room_category = RoomCategory::with('Room')->paginate(1);
return View::make('pages.roomlist', compact('room_category'));
你的看法:
@foreach($room_category as $category)
$category->name
@foreach($category->Room as $rooms)
$rooms->name
@endforeach
@endforeach
【讨论】:
以上是关于如何在laravel中对相关模型进行分页的主要内容,如果未能解决你的问题,请参考以下文章