How to paginate a “has many” relationship that is ordered?

后端 未结 2 1674
无人及你
无人及你 2020-12-31 17:02

I would like to paginate the following relationship (a Category having many Apps):

class Category extends Model
{
            


        
2条回答
  •  情歌与酒
    2020-12-31 17:31

    Have you tried this?

    $category = Category::first();
    $apps = $category->apps()->paginate(10);
    return view('example', compact('category', 'apps'));
    

    Then, on your view, you can just loop through the apps.

    @foreach ($apps as $app)
        {{ $app->id }}
    @endforeach
    
    {!! $apps->render() !!}
    

    If you want to set it as a relationship to category, you can use the setRelation method:

    $category = Category::first();
    $category->setRelation('apps', $category->apps()->paginate(10));
    return view('example', compact('category');
    

    Then in your view:

    @foreach ($category->apps as $app)
        {{ $app->id }}
    @endforeach
    
    {!! $category->apps->render() !!}
    

提交回复
热议问题