Laravel 5.1 在多对多关系中的条件


Laravel 5.1 Where Condition In Many To Many relationships

你好,我是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在我的数据透视表中。请提前提供帮助和感谢。

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

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

也许这会有所帮助

我认为下面的代码可能会对您有所帮助

$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);

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

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

然后会像这样简单

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

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

用户.php

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

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

我推荐第二个。有关更多信息,请遵循以下内容:

拉维尔有ManyThrough

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