Reputation: 4665
I have a product class with two category ids specified in it. I have the following relations set up and now I'm wanting to paginate the products
result set.
public function productsWithFirstCategory()
{
return $this->hasMany('App\Entities\Product', 'category1_id');
}
public function productsWithSecondCategory()
{
return $this->hasMany('App\Entities\Product', 'category2_id');
}
public function products()
{
return $this->productsWithFirstCategory->merge($this->productsWithSecondCategory);
}
public function getProductsPaginatedAttribute()
{
return $this->products()->paginate(20);
}
It appears I can't paginate the results because the merge does not return a query builder - how do I paginate a merged result set?
Upvotes: 0
Views: 358
Reputation: 40909
When you do $this->productsWithFirstCategory, you're accessing the result collection instead of the query builders, while paginate() can only work on query builders in your scenario.
In order to get what you need, you'll need to do a union of 2 queries. Just replace your products() method with:
public function products()
{
return $this->productsWithFirstCategory()->union($this->productsWithSecondCategory());
}
This will return the union of 2 query builders that you can later paginate in your getProductsPaginatedAttribute() method.
Upvotes: 1