Laravel Eloquent查询问题:筛选特定条件的User数据
解决方案
你的原查询存在两个关键问题:
- 子查询字段错误:
Compartment::select('country_id')应该选取id,因为user.compartment_id关联的是compartment.id,而非country_id - 逻辑条件错误:连续
where()会要求同时满足两个矛盾条件,你需要的是逻辑或,应该用orWhere()系列方法实现两类用户的并集。
下面提供两种符合要求的查询构建器写法:
方法一:基础子查询写法
$currentCountryId = Auth::user()->compartment->country_id; $query = User::whereNull('compartment_id') ->orWhereIn('compartment_id', function ($subQuery) use ($currentCountryId) { $subQuery->select('id') ->from('compartments') ->where('country_id', $currentCountryId); });
方法二:利用模型关联的优雅写法
借助User模型的compartment关联,用whereHas筛选符合条件的用户:
$currentCountryId = Auth::user()->compartment->country_id; $query = User::whereNull('compartment_id') ->orWhereHas('compartment', function ($query) use ($currentCountryId) { $query->where('country_id', $currentCountryId); });
额外注意事项
- 两种写法都直接返回查询构建器实例,无需调用
->get(),完全适配PowerGrid的需求 - 建议提前提取
$currentCountryId变量,避免重复调用关联关系,提升代码可读性 - 若当前用户可能没有关联的compartment,需添加空值判断避免报错:
$currentCountryId = Auth::user()->compartment?->country_id; $query = User::whereNull('compartment_id'); if ($currentCountryId) { $query->orWhereHas('compartment', fn($q) => $q->where('country_id', $currentCountryId)); }
内容的提问来源于stack exchange,提问作者kalview
相关产品推荐
相关产品推荐

