You need to enable JavaScript to run this app. Laravel 8关联ad_categories表加whereIn条件查询无返回数据问题
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8关联ad_categories表加whereIn条件查询无返回数据问题

问题原因

  1. LEFT JOIN + WHERE 过滤关联表逻辑错误
    你对LEFT JOIN的ad_categories表直接在WHERE子句加whereIn过滤,会导致LEFT JOIN特性失效:LEFT JOIN后没有匹配到关联分类的广告行,ad_categories.category_id字段值为NULL,NULL不满足IN [1,2,3,4,6,7,8]的条件,会被直接排除,最终实际执行效果等价于INNER JOIN。如果你要保留没有关联分类的广告,需要把过滤条件放到JOIN的ON子句里,而不是WHERE里。
  2. 手动JOIN和Laravel关联预加载with逻辑冲突
    你同时用了with('adCategories')预加载关联和手动leftJoin,两者是独立的逻辑:手动JOIN的过滤条件不会作用于预加载的adCategories关联数据,反而会导致主表查询结果重复。

正确实现方案

方案1:过滤「至少关联了指定分类的广告」,用whereHas

如果你的需求是只返回关联了$adsCategories中任意分类的广告,不需要保留无关联分类的广告,直接用Laravel关联查询的whereHas方法即可,不需要手动写JOIN:

$adsCategories = [1,2,3,4,6,7,8];

$data = Ad
    ::whereDate('expire_date', '>=', $date_start)
    ->whereDate('expire_date', '<', $date_end)
    ->orderBy($order_by, $order_direction)
    ->with('adCategories')
    ->with('creator')
    ->withCount('adLocations')
    // 过滤关联分类符合条件的广告
    ->whereHas('adCategories', function ($query) use ($adsCategories) {
        $query->whereIn('category_id', $adsCategories);
    })
    ->get();

方案2:保留所有符合日期条件的广告,仅预加载时过滤关联分类

如果你需要返回所有符合日期条件的广告,不管有没有关联分类,只是预加载的adCategories只返回指定分类的内容,用with的闭包过滤:

$adsCategories = [1,2,3,4,6,7,8];

$data = Ad
    ::whereDate('expire_date', '>=', $date_start)
    ->whereDate('expire_date', '<', $date_end)
    ->orderBy($order_by, $order_direction)
    // 预加载时过滤关联分类
    ->with(['adCategories' => function ($query) use ($adsCategories) {
        $query->whereIn('category_id', $adsCategories);
    }])
    ->with('creator')
    ->withCount('adLocations')
    ->get();

方案3:必须用手动LEFT JOIN的场景,把过滤条件放到ON子句

如果必须手动写LEFT JOIN,把关联表的过滤条件放到JOIN的ON子句里,不要放到WHERE,同时加distinct避免重复行:

$adsCategories = [1,2,3,4,6,7,8];

$data = Ad
    ::whereDate('expire_date', '>=', $date_start)
    ->whereDate('expire_date', '<', $date_end)
    ->orderBy($order_by, $order_direction)
    ->with('adCategories')
    ->with('creator')
    ->withCount('adLocations')
    ->distinct()
    // 过滤条件放到ON子句
    ->leftJoin('ad_categories', function ($join) use ($adsCategories) {
        $join->on('ad_categories.ad_id', '=', 'ads.id')
             ->whereIn('ad_categories.category_id', $adsCategories);
    })
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:45:07