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()'? –