0
這裏是原始的SQL查詢:Laravel 5. DB ::選擇工作原理
$best_price = DB::select('select id,product_id, shop_name, product_name, brand, weight_volume, min(price)
FROM (
select
p.id, p.product_id, p.shop_id, s.shop_name, pr.product_name, pr.brand, coalesce(pr.weight, pr.volume) weight_volume, p.price
from prices p
inner join (
select p1.id price_id,p1.product_id id, max(p1.created_at) maxed_date
from prices p1
where product_id= ?
group by p1.id, p1.product_id, p1.shop_id) grouped on grouped.maxed_date=p.created_at and grouped.price_id=p.id
join products pr on pr.id=p.product_id
join shop_names s on s.id=p.shop_id
group by p.id, p.product_id, p.shop_id) grouped
GROUP BY product_id,shop_name', [$request->product]);
在DBeaver我得到的"Metro C&C"
min(price)
一行的結果。
但如果我這樣做dd($best_price)
我得到以下結果:
array:2 [▼
0 => {#158 ▼
+"id": 46
+"product_id": 69
+"shop_name": "Metro C&C"
+"product_name": "Cream"
+"brand": ""Tastyland""
+"weight_volume": 0.22
+"min(price)": 300.0
}
1 => {#160 ▼
+"id": 47
+"product_id": 69
+"shop_name": "Klopshop"
+"product_name": "Cream"
+"brand": ""Tastyland""
+"weight_volume": 0.22
+"min(price)": 300.0
}
]
如果我去做
foreach($best_price as $best_price_id) {
return $best_price_id->shop_name;
};
我收到了以下結果"Metro C&C"
。
我有以下問題:
如何Laravel理解,有兩個結果與300最低價格(實際上這是結果,我期望的那樣),而DBeaver只提供了一個?我應該如何更改SQL查詢以獲得2行結果?
爲什麼
foreach
只返回第一行?
「爲什麼foreach只返回第一行?」因爲'return'終止循環! –
您的循環在返回時終止 –