2017-05-08 85 views
0

我想获取所有拥有一个或另一个角色的用户。我已经尝试过这样,它不起作用:Laravel结合where子句

$dentist = Role::where('name', 'dentist')->orWhere('name', 'local_admin')->first()->users()->where('clinic_id', $user->clinic_id)->get(); 

$dentist = Role::where('name', ['dentist', 'local_admin')->first()->users()->where('clinic_id', $user->clinic_id)->get(); 

$dentist = Role::whereIn('name', ['dentist', 'local_admin')->first()->users()->where('clinic_id', $user->clinic_id)->get(); 

是否有一个简单的解决方案呢?

+0

你错过了一个关闭广场布拉克第三和第四行代码? – Dinoop

回答

0

你必须define the relationshipRole的hasMany users那么你就可以访问userswith

$dentist = Role::with(['users' => function($query){ 
    $query->where('clinic_id', $user->clinic_id); 
    })]) 
    ->where('name', 'dentist') 
    ->orWhere('name', 'local_admin') 
    ->first(); 

这将走在你的角色模型

/** 
* Get the users for the role. 
*/ 
public function users() 
{ 
    return $this->hasMany(User::class); 
} 

这会去你的用户模型

/** 
* Get the role the user. 
*/ 
public function role() 
{ 
    return $this->belongsTo(Role::class); 
}