带闭包的 Laravel 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39563081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel query with closure
提问by Padron Leandro
I'm trying to query database and make a filter in a closure function, my model (Simplified) looks like this:
我正在尝试查询数据库并在闭包函数中创建过滤器,我的模型(简化)如下所示:
Products:
id,
sale_id
Sales:
id,
provider_id
Provider:
id
I wanna all the products from a specific provider, so i've constructed this my query:
我想要来自特定提供商的所有产品,所以我构建了这个我的查询:
Product::with(array
('sale'=>function($query){
$query->where('provider_id', '=', 1);
})
)->get();
the problem is that the result contains the right products with the sale, and the wrong products with the sale null, like this:
问题是结果包含销售的正确产品和销售为空的错误产品,如下所示:
[{
"id": 25,
"sale": null
},
{
"id": 26,
"sale": {
"id": 15,
"provider_id": 3
}
}]
products with sale:null are the products from another provider, I could filter them in memory, but I think there is a way to avoid the null results from the query, any clue?
带有 sale:null 的产品是来自其他供应商的产品,我可以在内存中过滤它们,但我认为有一种方法可以避免查询中的空结果,有什么线索吗?
回答by Adiasz
You need to add check about sale exists whereHas('sale')and apply condition about specific provider:
您需要添加有关销售存在的检查whereHas('sale')并应用有关特定提供商的条件:
Product::whereHas('sale', function($query) {
$query->where('provider_id', '=', 1); }
)->get();