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

Laravel:验证用户关联权限以实现站点登录授权

验证用户站点登录权限的条件查询实现

需求回顾

需要通过给定的user_id、location_id、sub_location_id验证以下条件,以此判断是否授予用户对应站点的登录权限:

  • 用户存在且处于激活状态
  • 用户已关联指定的子地点
  • 该子地点的关联记录处于激活状态

优化后的查询实现

方式1:从User模型出发,通过关联查询验证

$isAuthorized = User::where('user_id', $request->user_id)
    // 条件1:用户存在且激活
    ->where('status', 'Y')
    // 条件2+3:验证关联的子地点记录是否存在且激活
    ->whereHas('user_locations', function ($query) use ($request) {
        $query->where('location_id', $request->location_id)
              ->where('sub_location_id', $request->sub_location_id)
              ->where('status', 'Y');
    })
    ->exists();

// 根据结果处理权限
if ($isAuthorized) {
    // 授予登录权限
} else {
    // 拒绝登录请求
}

方式2:直接查询UserLocations表(更直观)

$isAuthorized = UserLocations::where('user_id', $request->user_id)
    ->where('location_id', $request->location_id)
    ->where('sub_location_id', $request->sub_location_id)
    // 条件3:子地点关联记录处于激活状态
    ->where('status', 'Y')
    // 条件1:关联的用户处于激活状态
    ->whereHas('user', function ($query) {
        $query->where('status', 'Y');
    })
    ->exists();

代码说明

  • 用exists()替代get():仅需判断是否存在符合条件的记录,无需返回完整数据集,性能更高效
  • whereHas()用于筛选满足关联表条件的主模型记录,精准匹配关联关系与状态要求
  • 两种实现均覆盖全部三个验证条件,可根据业务习惯选择使用

内容的提问来源于stack exchange,提问作者Lokesh M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:45:44