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以下返回正确的结果LT(当产品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...
}
}
}
}
你有没有尝试加入表而不是去存在检查? –
尚未尝试加入,但想知道发生了什么与此存在检查查询,看起来不错,但不工作,真的很奇怪/错误 – user259752
为什么在构建查询后使用'find()'? –