繁体   English   中英

如何在Laravel中将@foreach添加到SQL原始语句

[英]How to add @foreach to SQL raw statement in Laravel

我有一个数组$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])

您可以以这种方式作为示例-

$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]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM