fakhriahmedoff liked this thread
The problem is that you use wrong relation for this. Many to many is belongsToMany
and hasMany
works for 1 to many relationships.
So simply change relations to (and on User model you forgot return
):
public function users() {
return $this->belongsToMany('User', 'organizations_users');
}
public function organizations() {
return $this->belongsToMany('Organization', 'organizations_users');
}
Then a list of organizations for a user:
$user->organizations; // collection of Organization models
// and of course
$organization->users; // the other way around
Now, has
is supposed to fetch only those models that have the related ones:
$users = User::has('organizations')->get(); // returns users who have any organization related
$users = User::has('organizations', '>', 2)->get(); // returns users who have more than 2 organizations related
$users = User::whereHas('organizations', function ($q) {
$q->where('name', 'like', '%someName%');
})->get();
// returns users who have organizations matching the inner where clause (name column in this case)
The latter example could also query the pivot table itself if you need that
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community