1

I'm having issues with some relationships. I have the following situation

Product:

public function catalogues()

 {
     return $this->belongsToMany('App\Catalogue');
 }

public function category()
{
    return $this->belongsTo('App\Category');
}

Category:

 public function products()
   {
       return $this->hasMany('App\Product');
   }

Catalogue:

    public function products()
   {
       return $this->belongsToMany('App\Product');
   }

With a single query, I need to get all the categories that have products belonging to a certain catalogue. How can I achieve it?

1
  • You need join Commented Feb 19, 2018 at 12:47

2 Answers 2

3

Use whereHas():

Category::whereHas('products.catalogues', function($q) use($catalogueId) {
    $q->where('catalogues.id', $catalogueId);
})
->get();

Or:

Category::whereHas('products', function($q) use($catalogueId) {
    $q->whereHas('catalogues', function($q) use($catalogueId) {
        $q->where('id', $catalogueId);
    })
})
->get();
Sign up to request clarification or add additional context in comments.

3 Comments

This won't work either, it retrieves all the products from those categories.
@Dani it can't retrieve any products, it will return categories only. Do not modify the code, use it as is.
Thanks. In Laravel Backpack, I was able to use $this->crud->query = $this->crud->query->whereHas('contactTags', function($q) use($tagId) { $q->where('tag_id', $tagId); });
0

You need whereHas and

    Category::whereHas('products')
  ->with(['products' => function($query) use ($id){
        $query->with('catalogues' => function($query) use ($id){

         $query->where('catalogues.id',$id);

      });

   }])
  ->get();

Hope this helps.

6 Comments

Thank you, but actually what I need to do later is to loop it by category, not by products. That's why I'm a little confused, as I tried the "with" method, which works perfectly if I just pick the products, not if I join the catalogues too as there's no relationship b/w catalogues and categories
@Dani I have updated the answer have a look. it may helps you
Amazing, this works! Thank you, you saved me from a huge headache :)
@Dani I am glad this works for you. If this really worked for you can accept this answer.
@Dani this can't possibly work for you because this code will give you an error and with() will load the data instead of filtering categories by related data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.