【问题标题】:Laravel 5.3 hasManyThrough through an intermediate tableLaravel 5.3 hasManyThrough 通过一个中间表
【发布时间】:2016-10-25 11:51:18
【问题描述】:

我有如下表关系:

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?如果没有,还有其他方法吗?

【问题讨论】:

  • 您的方案是多对多关系。 hasManyThrough用于访问距离关系,比如在“组织有很多用户,用户有很多帖子,所以你可以通过组织hasManyThrough帖子来间接从用户访问组织的帖子。”。

标签: php laravel laravel-5.3


【解决方案1】:

这是many to many 关系。

用户模型:

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

组织模式:

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

获取所有用户及其组织:

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

【讨论】:

  • 是的,我试图描述多对多的关系。谢谢你指出这一点。像魅力一样工作。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2014-06-15
    • 2019-04-17
    • 1970-01-01
    • 2021-10-15
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多