Wednesday, January 19, 2022

[FIXED] retrieve nested eloquent relations items

Issue

I have 4 models connected with hasMany relations as below:

Brand -> hasMany -> Categories -> hasMany -> subCategories -> hasMany -> products

I want to retrieve the categories that their subcategories have one or more products.

I tried querying relationship existence with has and/or whereHas but no luck.

Thanx for your advice,


Solution

Using has() dot annotation, should do the trick for you.

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


Answered By - mrhn

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.