我有一个数组$shop_ids
,所以我想循环并将这些id添加到SQL语句的子查询中。 SQL子查询的数量应该等于id的数量。
我希望这样的查询,但显然@foreach
不起作用,只是成为SQL查询的一部分:
DB::select('select
pr.product_name,
pr.brand,
coalesce(pr.weight, pr.volume) wv,
sli.quantity
{{@foreach ($shop_ids as $id)
,{{(select
p.price
from prices p
inner join (
select p1.product_id id, max(p1.created_at) maxed_date
from prices p1
group by p1.product_id, p1.shop_id) grouped on grouped.maxed_date=p.created_at
join shop_names s on s.id=p.shop_id
where p.product_id=sli.product_id
and s.id=$id)}}}}
from shopping_list_items sli
join products pr on pr.id=sli.product_id
where sli.shopping_list_id= :slid
order by 5 asc', ['slid'=>$this->id])
答案 0 :(得分:2)
你可以这样做 -
$ids_query = '';
// generate the queries in loop
foreach ($shop_ids as $id) {
$ids_query .= ", (select ..... where .. and s.id=$id)";
}
// use in the main query
DB::select("select
...,
sli.quantity
$ids_query
from shopping_list_items sli
...
order by 5 asc", ['slid'=>$this->id]);