2017-05-08 83 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); 
}