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
相关产品推荐
相关产品推荐

