Laravel 5如何与hasMany关系分页

时间:2018-03-30 19:52:32

标签: laravel relationship

我有这样的关系;

public function foods() {
    return $this->hasMany('App\models\food\food', 'category_id', 'id');
}

我的控制器文件内容;

$datas = food_category::where('slug', $slug)->with('foods')->paginate(12);

但是所有数据中的传入数据都会导致性能下降。我想分页应用关系数据。

2 个答案:

答案 0 :(得分:0)

如果您要对foods进行分页,请尝试为其添加单独的方法:

型号:

class food_category
{
    public function getFoodsPaginatedAttribute()
    {
        return $this->foods()->paginate(12);
    }
}

控制器:

$datas = food_category::where('slug', $slug)->get();

查看:

@foreach ($datas as $data)
    @foreach ($data->foods_paginated as $food)
        {{ $food->name }}
    @endforeach
@endforeach

答案 1 :(得分:0)

将分页集合传递给视图:

//view
@foreach ($datas as $data)
    // do what you need
@endforeach
//link
{{$datas->links()}}