简体   繁体   English

Laravel组合了where子句

[英]Laravel combined where clause

I would like to fetch all users which have one role or another. 我想获取所有具有一个或另一个角色的用户。 I have tried like this and it doesn't work: 我已经尝试过这种方法,但它不起作用:

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

Is there a simple solution for this? 有一个简单的解决方案吗?

You have to define the relationship Role hasMany users then you can access users with with 你必须定义关系 Role的hasMany users ,那么你可以访问userswith

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

This would go in you Role model 这将成为您的榜样

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

This would go in your User model 这将在您的用户模型中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM