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

Laravel中doesntHave方法返回空结果的问题求助

问题分析与解决方法

你的问题出在 whereDoesntHave('productPurchases') 的用法上——这个方法是检查该商品是否完全没有任何 productPurchases 关联记录,但你实际想要的是该商品没有对应指定 client_id 的 productPurchases 记录。

当你移除 whereDoesntHave 后看到的空 product_purchases 数组,只是因为你在 with 里过滤了当前 client_id 的关联,并不代表这些商品完全没有其他 client 的购买记录。所以原查询会把那些有其他购买记录的商品排除,导致返回空结果。

正确写法

需要给 whereDoesntHave 传入闭包,加上和 with 中一致的 client_id 过滤条件,这样就能精准筛选出没有当前客户购买记录的商品:

$products = Product::where('product_type_id', $typeId)
    ->with([
        'productPurchases' => function($q) use ($clientId) {
            $q->where('client_id', $clientId);
        },
        'productType'
    ])
    ->whereDoesntHave('productPurchases', function($q) use ($clientId) {
        $q->where('client_id', $clientId);
    })
    ->get();

补充说明

如果你确实需要筛选完全没有任何购买记录的商品,那原写法是对的,但根据你的描述,显然你的需求是前者——排除当前客户已购买过的商品。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:13:08