Laravel结合where子句

时间:2017-05-08 21:54:51

标签: php laravel

我想获取所有具有一个或另一个角色的用户。我试过这样的事情并没有起作用:

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

这有一个简单的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您必须define the relationship Role hasMany users然后您可以with

访问users
$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);
}