James A James A - 1 month ago 15
PHP Question

Laravel 5.3 hasManyThrough through an intermediate table

I have the following table relationship:

organizations
id - integer

organization_users
organization_id - integer (FK)
user_id - integer (FK)

users
id - integer


I am trying to get all the users of an organization through eloquent relationships. Here is my Organization.php model with its relationships:

class Organization extends Model
{
public function Users(){
return $this->hasManyThrough('App\User', 'App\OrganizationUser',
'organization_id', 'user_id', 'id');
...
}


I have tried many combinations of that relationship such as

return $this->hasManyThrough('App\User', 'App\OrganizationUser',
'user_id', 'organization_id', 'id');


But all turn up somewhat the same error (this one is from the first query):

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not
found: 1054 Unknown column 'organization_users.id' in 'on clause' (SQL: select
`users`.*, `organization_users`.`organization_id` from `users` inner join
`organization_users` on `organization_users`.`id` = `users`.`user_id` where
`organization_users`.`organization_id` = 1)'


Is it possible that I can have the relationship retrieve the user_id to query on the users table instead of Laravel trying to retrieve organization_users.id? If not is there another way around this?

Answer

This is many to many relationship.

User Model:

public function organizations()
{
    return $this->belongsToMany('App\Organization','organization_users');
}

Organization Model:

  public function users()
   {
        return $this->belongsToMany('App\User','organization_users');
   }

To, get all the users with their organizations:

$users=User::with('organizations')->get();
foreach($users as $user)
{
   print_r($user->name);
   foreach($user->organizations as $organization)
   {
     print_r($organization->name);
   }
}
Comments