Laravel Multiple Unions

后端 未结 3 1592
天涯浪人
天涯浪人 2021-01-13 10:38

I\'m having an issue adding a query with multiple Unions the \"laravel way\".

The I am trying to accomplish a query equivalent to the one generated by the following:

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 11:03

    Your unionAll calls are indeed getting nested. One solution is to create a subquery in the for loop, and then unionAll that subquery to the main query after it's been defined. Then you run get on the whole shebang when you're done, like so:

    $ips_list = DB::table('ips')->where('network', '=', '1')->where('used', '=', '0')->limit(5);
    
    for($n = 1; $n < $total_networks; $n++){
        $ip_list_subquery = DB::table('ips')
                 ->where('network', '=', $n)
                 ->where('used', '=', '0')
                 ->limit(5);
        $ips_list = $ips_list->unionAll($ip_list_subquery);
    }
    $ips = $ips_list->get();
    

    So, effectively, you're chaining the unionAll calls:

    $a->unionAll($b)->unionAll($c)->unionAll($d)...

    rather than nesting them:

    $a->unionAll($b->unionAll($c->unionAll($d...))))

提交回复
热议问题