0

I have a relationship in my app where a organisation can have many users and many users can have many organisations, in my model this looks like this,

Organisation.php

public function users() {
    return $this->belongsToMany('User')->withPivot('is_admin');
}

User.php

public function organisations() {
        $this->belongsToMany('Organisation');
}

What I am wanting to do, is run a query that has multiple where clauses and then return the row data and any pivot data.

For one where clause I would do the following,

$org = Organisation::find(1);
$orgUsers = $org->users();

What I cannot figure out is how I would user multiple wheres if I needed too?

1
  • I don't really get what you want here. And your code isn't even valid (you forgot to return $this->belongsToMany('Organisation') and to $org->users()->get() or $org->users. Do you want to apply multiple where clauses to the organization, and then get its users? Or do you want its users, but applying other where clauses to it? Commented Oct 17, 2014 at 14:24

1 Answer 1

1

Assuming you want to add the wheree()'s to users, it might look something like this (Eager loading the users)

$constraints = ['fname' => 'john', 'lanme' => 'doe'];

$org = Organisation::with(['users' => function($query) use ($constraints){

    foreach($constraints as $field => $val)
        $query->where($field, $val);

    // Or if you just want admin users using your pivot table field
    $query->pivot->where('is_admin', true);

}])->find($id);

Or, you could get them all, and filter them if you need a collection of users, and a collection of admins

$org = Organisation::with('users')->find($id);

$admins = $org->users->filter(function($user){ return $user->pivot->is_admin });
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.