我正在尝试在 Laravel 中使用具有嵌套关系的 orWhereHas
方法,但我没有得到我期望的结果。我是否误解了如何使用此方法?
我的关系设置如下:
Product
-> hasOne uniqueItem
-> hasMany fulfillmentCenterUniqueItems
-> hasMany skus
-> hasOne uniqueItem
-> hasMany fulfillmentCenterUniqueItems
我正在尝试通过从数据库中检索包含 uniqueItems
且具有 的产品来测试
,whereHas
和 orWhereHas
方法>uniqueItemFulfillmentCenterid = 7089
或包含 sku
的产品,包含 uniqueItem
,具有 uniqueItemFulfillmentCenter
与 id = 7412
。
根据我数据库中的数据,这个查询的结果应该是两个产品。产品 ID 105 和 239。
这是我正在使用的 Eloquent 代码:
$product = Spire_models\Product
::whereHas('uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7089);
})
->orWhereHas('skus.uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7412);
})
->get()->toArray();
出于某种原因,这只返回产品 ID 105,而不是 105 和 239。此函数生成的 sql 是:
select * from `products` where `products`.`deleted_at` is null and (select count(*) from `unique_items` where `products`.`unique_item_id` = `unique_items`.`id` and (select count(*) from `fulfillment_center_unique_items` where `fulfillment_center_unique_items`.`unique_item_id` = `unique_items`.`id` and `id` = 7089 and `fulfillment_center_unique_items`.`deleted_at` is null) >= 1 and `unique_items`.`deleted_at` is null) >= 1 and (select count(*) from `skus` where `skus`.`product_id` = `products`.`id` and (select count(*) from `unique_items` where `skus`.`unique_item_id` = `unique_items`.`id` or (select count(*) from `fulfillment_center_unique_items` where `fulfillment_center_unique_items`.`unique_item_id` = `unique_items`.`id` and `id` = 7412 and `fulfillment_center_unique_items`.`deleted_at` is null) >= 1 and `unique_items`.`deleted_at` is null) >= 1 and `skus`.`deleted_at` is null) >= 1
这个 sql 生成不正确,还是我误用了 orWhereHas
方法?在我看来,OR
语句似乎没有正确放置在 sql 中。
如果我删除 orWhereHas
方法,一切都会按预期进行。例如,如果我运行这个:
$product = Spire_models\Product
::whereHas('uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7089);
})
->get()->toArray();
我正确地取回了产品 ID 105。如果我运行此命令:
$product = Spire_models\Product
::whereHas('skus.uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7412);
})
->get()->toArray();
我正确地取回了产品 ID 239。因此,查询的各个部分都可以正常工作,但是当我尝试将它们与 orWhereHas
组合时,我似乎得到了意想不到的结果。知道为什么吗?
编辑
根据评论,这看起来像是一个错误。我能够通过重写代码以使用 where
和 orWhere
来暂时解决这个问题。这是临时解决方案:
$product = Spire_models\Product
::where(function ($query)
{
$query->whereHas('uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7089);
});
})
->orWhere(function ($query)
{
$query->whereHas('skus.uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7412);
});
})
->get()->toArray();
最佳答案
这是一个错误,现在已通过此 PR 修复 https://github.com/laravel/framework/pull/8171
从5.0.21版本就可以了
关于php - Laravel 或 WhereHas 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28241584/