如何在laravel中对相关模型进行分页

时间:2015-05-28 08:03:28

标签: laravel laravel-4 model pagination eloquent

我有两个型号,分别是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循环下对这些房间进行分页。感谢

2 个答案:

答案 0 :(得分:0)

要实现您想要的功能,您必须获取所有房间类别,循环浏览它们,然后遍历每个房间类别的房间。

这是示例代码:

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

答案 1 :(得分:0)

如果您使用的是paginate,则不需要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() }}