0

I have three models. Category, Product, and variation. A category has many products and a product has many variations. What i'm trying to do it get the categories that have at least one product that has at least one variation. I have been able to do that with this code:

$categories = Category::with(['products', 'products.variants'])
        ->whereHas('products', function($query) {
            $query->whereHas('variants', function() {});
        })
        ->get();

But, and here's the tricky part, I want to exclude products that don't have any variations. I can't seem to do this without excluding the entire category.

In short. The result set will only include categories that have at least one product that has at least one variation. And the (sub) result set of products will only include products that have at least one variation.

Sorry if this is hard to understand. I honestly don't know how to word such a strangely specific issue.

Cole
  • 165
  • 2
  • 11

1 Answers1

1

Figure it out based on this answer https://stackoverflow.com/a/19921418/5465657

My working code

$categories = Category::with(['products' => function($query) {
        $query->whereHas('variants', function() {});
    }, 'products.variants'])
        ->whereHas('products', function($query) {
            $query->whereHas('variants', function() {});
        })
        ->get();
Community
  • 1
  • 1
Cole
  • 165
  • 2
  • 11