Laravel 5.3 hasManyThrough通过一个中间表

时间:2016-10-25 03:34:15

标签: php laravel laravel-5.3

我有以下表格关系:

organizations
  id - integer

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

users
  id - integer

我试图通过雄辩的关系来吸引组织的所有用户。这是我的Organization.php模型及其关系:

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

我尝试了很多这种关系的组合,比如

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

但是所有错误都出现了同样的错误(这个错误来自第一个查询):

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)'

我是否有可能让关系检索user_id以在users表上查询而不是Laravel尝试检索organization_users.id?如果没有,还有另一种解决方法吗?

2 个答案:

答案 0 :(得分:1)

这是many to many关系。

用户模型:

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

组织模式:

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

To,让所有用户加入他们的组织:

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

答案 1 :(得分:0)

您所描述的内容看起来可能是“多对多”关系。

https://laravel.com/docs/5.3/eloquent-relationships#many-to-many