James A James A - 1 year ago 108
PHP Question

Laravel 5.3 hasManyThrough through an intermediate table

I have the following table relationship:

id - integer

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

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 Source

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:

foreach($users as $user)
   foreach($user->organizations as $organization)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download