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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:06:18