You need to enable JavaScript to run this app. Laravel高级关联查询:affiliates与affiliatesHistory的条件筛选实现
优惠活动
大模型
产品
解决方案
定价
更多

Laravel高级关联查询:affiliates与affiliatesHistory的条件筛选实现

完整查询实现方案

落地规则对齐

  • 保留原有业务筛选逻辑:排除关联了Installed earlier、Uninstalled / Installed earlier状态历史的affiliate
  • 满足基础查询要求:仅返回存在至少1条关联affiliatesHistory记录的affiliate
  • 补全新增排除规则:剔除「关联history总条数为1、且该唯一记录状态为uninstalled」的affiliate

可直接运行的代码实现

$affiliates = $user->affiliates()
    // 基础约束:必须存在关联的历史记录
    ->whereHas('affiliatesHistory')
    // 原有筛选逻辑:排除带两类指定状态历史的记录,替换原易出现优先级错误的orWhere写法
    ->whereDoesntHave('affiliatesHistory', function ($query) {
        $query->whereIn('status', [
            'Installed earlier',
            'Uninstalled / Installed earlier'
        ]);
    })
    // 新增约束:排除「仅存在1条uninstalled状态历史、无其他状态历史」的记录
    ->where(function ($query) {
        // 匹配待排除的场景:
        // 1. 没有任何非uninstalled状态的关联历史(所有历史均为uninstalled)
        $query->whereDoesntHave('affiliatesHistory', fn($q) => $q->where('status', '!=', 'uninstalled'))
            // 2. uninstalled状态的历史记录总数恰好为1
            ->whereCount('affiliatesHistory', fn($q) => $q->where('status', 'uninstalled'), '=', 1);
    }, 'not')
    ->get();

实现说明

  • 原代码中拼接orWhere的写法存在SQL逻辑优先级隐患,未嵌套的or会打乱前面的条件匹配规则,替换为whereIn在不改变原有筛选逻辑的前提下,大幅降低语法错误概率
  • 新增排除规则没有笼统判断全量uninstalled历史,而是通过两层精准判断定位目标排除对象:
    1. 先过滤出所有关联历史均为uninstalled状态的affiliate,避免误排除多uninstalled记录的合法数据
    2. 再统计这类对象里uninstalled状态的记录数,仅将数为1的对象纳入排除范围,完全匹配需求的排除边界
  • 相比先查询关联计数再做过滤的写法,上述关联判断会将统计逻辑直接下推到SQL层,不会触发额外的全表遍历,数据量较大时查询效率更优

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 14:54:03