【问题标题】:Laravel 5.1 Where Condition In Many To Many relationshipsLaravel 5.1 多对多关系中的条件
【发布时间】:2016-03-15 06:43:41
【问题描述】:

你好,我是 Laravel 的新手,我有以下模型:

organizations
-----------------
id
name

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

users
-----------------
id
name

organization_user
------------------
user_id
organization_id

组织和用户之间存在多对多的关系。现在我想找到用户所属的组织。如何为关系中的用户添加 where 条件。

例如,我想查找登录用户的所有组织。我正在尝试以下方法:

$organisations       = Organisation::where('user_id' , '=' , $user->id)->paginate(10);

但它不起作用,因为 user_id 在我的数据透视表中。请帮助并提前致谢。

【问题讨论】:

  • 尝试在用户模型中添加反向关系而不是$user->organization(),我认为这是最简单的处理方法。

标签: php mysql laravel-5 eloquent


【解决方案1】:

我认为您需要在代码中使用 wherePivot() 函数,例如

$organisations       = Organisation::with(array('user'=> function($query) use ($user){ 
                                $query->wherePivot('user_id' , '=' , $user->id);     
                            }) )->paginate(10);

这可能会有所帮助

【讨论】:

  • 您好@Jitendra 感谢您的快速回复。我尝试了您的解决方案,但出现此错误: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in 'where clause' (SQL: select count(*) as aggregate from organisations where pivot = user_id )
【解决方案2】:

我认为下面的代码可以帮助你

$organisations = Illuminate\Support\Facades\DB::table('organizations')
    ->join('organization_user', 'organizations.id', '=', 'organization_user.organization_id')
    ->join('users', 'users.id', '=', 'organization_user.user_id')
    ->where('users.id', '=', $user->id)
    ->paginate(10);

【讨论】:

    【解决方案3】:

    我认为您需要将此添加到您的 User Model

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

    然后就会像这样简单

    $organizations = Auth()->user()->organizations; 
    

    【讨论】:

      【解决方案4】:

      首先在模型中添加你的关系:

      用户.php

      public function organizations()
      {
      return $this->hasMany(organization_user::class);
      }
      

      或者

      public function organizations()
      {
      return $this->hasManyThrough(organizations::class,organization_user::class);
      }
      

      我推荐第二个。欲了解更多信息,请点击:

      Laravel hasManyThrough

      请注意,使用相同的组织模型创建关系

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-02
        • 1970-01-01
        • 1970-01-01
        • 2016-06-03
        • 2013-11-13
        • 2016-02-21
        • 2015-07-20
        • 1970-01-01
        相关资源
        最近更新 更多