Laravel Eloquent pagination on relationships

前端 未结 3 705
梦如初夏
梦如初夏 2021-01-05 06:48

I am trying to paginate a Eloquent relationship like this:

 $query = Product::find(1)->options()->paginate();

But I get the following

相关标签:
3条回答
  • 2021-01-05 06:53

    Create a custom length-aware paginator.

    $options = new LengthAwarePaginator(Product::find(1)->options()->
                ->skip(($request->input('page', 1) - 1) * 10)->take(10)->get(),
                Product::find(1)->options()->count(), 
                10, $request->input('page', 1),
                [
                    // paginator options here
                ]);
    
    0 讨论(0)
  • 2021-01-05 07:01
    $query = Product::find(1)->get()->options()->paginate(); 
    

    Try adding get

    0 讨论(0)
  • 2021-01-05 07:06

    You can not lazy load relational pagination like that, instead in your Product Model put the following function below your options has many relationship

    public function getOptionsPaginatedAttribute()
    {
        return $this->options()->paginate(10);
    }
    

    This will allow you to call the pagination on your relational data by

    $product->options_paginated
    
    0 讨论(0)
提交回复
热议问题