1

Let's say I have the relation: Role has many Users. Role and user stores a code value.

If I want to select all roles that have users with same code, how would be this query using whereHas clause?

What I tried:

$roles = Role::whereHas('users', function ($users) {
    // Obviously doesn't work but it is what I need to access.
    $code = $users->first()
        ->role
        ->code;

    return $users->where('code', $code);
})->get();
6
  • Is this to see how it would would using the whereHas method, or just to have this working regardless of the method used? Commented Sep 18, 2018 at 14:14
  • @thisiskelvin Actually this is a symbolic example to a more complex one that I have to use whereHas. So it's required. Commented Sep 18, 2018 at 14:16
  • 2
    I would like to see the result of this. I think the problem is finding out a way to access the current role iteration within whereHas() to be able to use within the query. Commented Sep 18, 2018 at 14:24
  • @thisiskelvin yeah, agree Commented Sep 18, 2018 at 14:26
  • Are you anywhere closer to finding an answer? Commented Sep 18, 2018 at 15:46

1 Answer 1

1

Use this:

$roles = Role::whereHas('users', function ($query) {
    $query->whereColumn('users.code', 'roles.code');
})->get();
Sign up to request clarification or add additional context in comments.

7 Comments

If I need to use the code value for another operation, like filter a php array, I couldn't use this approach?
For example: $code = $query->getColumn('roles.code');
I don't understand your question. You can get the code from the result: foreach($roles as $role) { echo $role->code; }
You've missed the $query in function parameter
@JonasStaudenmeir no, I need the value of code inside whereHas Closure.
|

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.