Search code examples
phplaravellaravel-5.3unions

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.


Solution

  • 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.