You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过关联表查询拥有doctor角色的用户(Laravel模型实现)

获取拥有Doctor角色的用户查询实现方案

先确认模型关联

在User模型里先定义好和Role的多对多关联(关联中间表是user_roles):

// app/Models/User.php
public function roles()
{
    return $this->belongsToMany(Role::class, 'user_roles', 'user_id', 'role_id');
}

完善showDoctor方法的查询逻辑

直接通过关联筛选就能拿到目标用户,两种常用写法:

写法1:仅获取符合条件的用户数据

public function showDoctor ()
{
    $users = User::whereHas('roles', function ($query) {
        $query->where('name', 'doctor');
    })->get();

    return $users;
}

写法2:同时获取用户关联的角色信息(避免N+1查询)

如果需要返回用户的角色详情,加上with('roles')预加载关联:

public function showDoctor ()
{
    $users = User::with('roles')
        ->whereHas('roles', function ($query) {
            $query->where('name', 'doctor');
        })
        ->get();

    return $users;
}

关键说明

  • whereHas的作用是筛选出存在指定关联条件的用户,这里就是筛选拥有name为doctor的角色的用户。
  • 预加载with('roles')是为了避免循环查询用户时重复查角色表,提升性能。

内容的提问来源于stack exchange,提问作者penina kinanu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:45:37