Laravel Eloquent Relationship Paging

I am trying to break up relationships such as:

$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 confirmed that the code $query = Product::find(1)->options() returns a set of options. The $query object seems to be of type hasMany . Below are the classes of models that I use.

 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'); } } 

Doesn't the eloquent return paginated results for relationships?

+5
source share
3 answers

You cannot lazy such a relational breakdown on load, but instead, in your product model add the following function to your options, which has many relationships

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

This will allow you to paginate your relational data into

 $product->options_paginated 
+15
source

Create a custom length indicator.

 $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
source
 $query = Product::find(1)->get()->options()->paginate(); 

Try to add get

-3
source

Source: https://habr.com/ru/post/1201118/


All Articles