Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - How to use union in more than two tables/queries with Query Builder or Eloquent?

I have 10 tables that i want 'union'. Here my table name with same fields.

sell_2007
sell_2008
sell_2009
...
sell_2015
sell_2016

In the example given by laravel do union in the two tables only (https://laravel.com/docs/5.3/queries#unions), how if the table more than two tables/queries? In my case there are 10 tables. How to do that with Query Builder or Eloquent?

Thank you for your help.

like image 985
Fredy Avatar asked Mar 10 '23 17:03

Fredy


1 Answers

You can add multiple unions like this;

$first = DB::table('sell_2007');
$second = DB::table('sell_2008');

$users = DB::table('users')
        ->union($first)
        ->union($second)
        ->get();

You may find that you get better perfomance to union the tables using RAW SQL query.

like image 88
TedRed Avatar answered Mar 12 '23 06:03

TedRed