【发布时间】:2018-03-11 13:44:32
【问题描述】:
产品型号
public function country() {
return $this->hasMany('App\Models\ProductCountry', 'product_id', 'id');
}
控制器
$product = Product::where('mall_' . $this->mall_id, '=', 1)
->whereHas('country', function ($i) use ($me) {
return $i->where('country_id', $me->country_id);
})
->find($key);
原始 SQL:
select * from `product` where `mall_3` = '1' and exists (select * from `product_country` where `product_country`.`product_id` = `product`.`id` and `country_id` = '109') and `product`.`id` = '3' and `product`.`deleted_at` is null limit 1
上面的SQL没有返回结果(当产品id = 3时
下面的 SQL 返回正确的结果(当产品 id = 6 时)
select * from `product` where `mall_3` = '1' and exists (select * from `product_country` where `product_country`.`product_id` = `product`.`id` and `country_id` = '109') and `product`.`id` = '6' and `product`.`deleted_at` is null limit 1
不知道,查询好像没问题
以前的项目我也遇到了这个问题,最后我再次使用查找和循环而不是使用 whereHas,但是这次我再次遇到这个问题并尝试找出原因,但是浪费了几个小时,仍然没有线索,下面是一种解决方法(忽略错误?)
$products = array();
foreach ($request->get('quantity') as $key => $var) {
if ($var > 0) {
$product = Product::with(['country'])->where('mall_' . $this->mall_id, '=', 1)
->find($key);
foreach ($product->country as $c) {
if ($c->country_id == $me->country_id && !isset($products[$product->id])) {
//Do something here...
}
}
}
}
【问题讨论】:
-
您是否尝试过加入表格而不是进行存在检查?
-
尚未尝试加入,但想知道这个存在检查查询发生了什么,看起来不错但不起作用,真的很奇怪/错误
-
构造查询后为什么要使用
find()? -
我使用 find 是因为想找到确切的产品,我使用 whereHas 是因为我也希望查询做 VALIDATION,确保没有产品从另一个国家订购,我认为这种方式会阻止用户检查在订单表单中编辑产品 ID 的元素
-
嗨,我认为你会从 laravel 收集方法中得到很好的利用 (laravel.com/docs/5.4/collections#available-methods)。特别是 'map' 和 'filter' 方法。
标签: php mysql laravel laravel-5 laravel-eloquent