php - Merging merged querybuilders in laravel 5.2 to then paginate

115

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 theproducts 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?

17

Answer

Solution:

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.

People are also looking for solutions to the problem: php - Class validator not found in respect validation Lib

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.