Rediska's avatar

how to get data from a double relationships?

I have tables of categories, products and colors. I apply a many-to-many relationship. I need to get all categories that have black colored products.

To get categories that have products I do this:

$categories = Category::has('products')->get();

How can I expand my query to add a search based on color? I try this, but nothing works.

$categories = Category::has('products')->whereHas('colors', function ($query){
            $query->where('title', 'black');
        })->get();
0 likes
5 replies
jlrdw's avatar

I don't have the link, but search and @martinbean and @tray2 has has some good post on product variations similar to what you ask.

MichalOravec's avatar
Level 75

This should work:

$categories = Category::whereHas('products.colors', function ($query) {
    $query->where('title', 'black');
})->get();
1 like
Rediska's avatar

@MichalOravec I want to ask you one more question. Your option is completely working!

But there is a nuance - my product has only one category (usually the final one), for example, “t-shirts”. And in the categories table there is a column indicating the parent category. Like that:

id      category_id       parent_id                title
1            101                     10                      cloth
2           1011                   101           t-shirts and polos
3           1012                   101           trousers and jeans
4          10111                 1011                  t-shirts

How then can I get not only the category “black T-shirts”, but also “black T-shirts and polos” and “black clothes”?

Please or to participate in this conversation.