in my database structure each Category
belongs to a user or multiple Users
, each user belongs to a Role
or multiple roles, and then each user have a Post
or multiple posts which this model belongs to Category
,
tip: Category
not belongs to Role
model
simply we can get posts or categories from this structure but i want to get all posts based on users specific role
and fetching this posts belong to which categories
my implemented code is not correct and that return empty list:
$posts = Category::whereHas('users', function ($query) {
$query->with(['user'=>function($q){
$q->with(['roles'=>function($u){
$u->whereLabel('is-admin');
}]);
},'posts']);
})->get();
My Answer:
>whereHas('roles', function ($query) {
$query->where('name', 'admin');
});
})->with('posts')->get();
This code is trying to get all categories that have users with the role of 'admin', and then eager load the posts for those categories. However, since categories do not directly belong to roles, this code will not work as expected.
Instead, you can try the following code to achieve the desired result:
php
$posts = Post::whereHas('category.users.roles', function ($query) {
$query->where('name', 'admin');
})->with('category')->get();
This code will get all posts that belong to categories where the users have the role of 'admin'. It will also eager load the category for each post so you can access the category information as well.
Rate this post
5 of 5 based on 6309 votesComments