Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.

fakhriahmedoff liked this thread

1

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

Last updated 2 years ago.
0

How can i order $users by organizations name?

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.