Laravel Eloquent pagination on relationships

2019-02-13 21:31发布

I am trying to paginate a Eloquent relationship like this:

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

But I get the following error:

Fatal error: Call to a member function getCurrentPage() on a non-object

I have confirmed that the code $query = Product::find(1)->options() returns a collection of options. The $query object seems to be of type hasMany. Below are the model classes I am using.

class Product extends Eloquent
{

    protected $table = 'products';

    public function options ()
    {
        return $this->hasMany('ProductOption', 'product_id');
    }
}

class ProductOption extends Eloquent
{
    protected $table = 'product_options';

    public function product()
    {
        return $this->belongsTo('Product', 'product_id');
    }
}

Does eloquent not return paginated results for relationships?

3条回答
Melony?
2楼-- · 2019-02-13 22:21

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
查看更多
孤傲高冷的网名
3楼-- · 2019-02-13 22:25

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
            ]);
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-13 22:29
$query = Product::find(1)->get()->options()->paginate(); 

Try adding get

查看更多
登录 后发表回答