0

Here the situation.

I have a user table, a role table (different users can have the same role) and a post table (different users can be linked to a same post - multi authors post). I also have two join tables that link user and role and user and post. I have built all relationships (many-to-many).

But now I try to get all users that have a particular role ('id' = 2 for example) and have contributed to a particular post ('id' = 45 for example).

I can do it with one criteria :

$roles = App\Role::where('id', 2)->first();
foreach ($roles->users as $user) {

}

But I didn't find the solution with two criterias (role id and post id).

1 Answer 1

3

You can use relationship existence to to achieve your goal. And the whereHas() function is for checking relationship existence.

Assuming that you have defined relationships on models

$roleId = 2;
$postId = 45;

$users = User::whereHas('role', function($query) use ($roleId) {
    $query->where('id', $roleId);
})
->whereHas('post', function ($query) use ($postId) {
    $query->where('id', $postId);
})
->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.