Eloquent Nested Where Statement
For an online competition with the goal of photographing certain objects I've got users uploading pictures of objects, where the objects have a category and a subcategory. A user'
Solution 1:
You want to get categories with pictures that belong to specified user, so you do this (a bit verbose):
Category::with(['subcats', 'subcats.objects' => function ($q) use ($user) {
$q->with(['pictures' => function ($q) use ($user) {
$q->where('user_id', $user->id);
}]);
}])
->whereHas('subcats', function ($q) use ($user) {
$q->whereHas('objects', function ($q) use ($user) {
$q->whereHas('pictures', function ($q) use ($user) {
$q->where('user_id', $user->id);
});
});
})
->get();
You need to use nested with() closures here, because you can load more than two levels of relationship with using dot notation.
If you don't need to load pictures and subcategories data, just remove with() part.
If you also want to filter subcategories, add a closure to with() for subcats.
Post a Comment for "Eloquent Nested Where Statement"