How to union more than two tables in laravel?

by darrion.kuhn , in category: PHP Frameworks , 3 months ago

How to union more than two tables in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 3 months ago

@darrion.kuhn 

In Laravel, you can perform a union on more than two tables using the union() method provided by the Query Builder. Here is an example of how you can union three tables in Laravel:

1
2
3
4
5
6
7
8
9
$firstTable = DB::table('table1');
$secondTable = DB::table('table2');
$thirdTable = DB::table('table3');

$result = $firstTable
    ->select('column1', 'column2')
    ->union($secondTable->select('column1', 'column2'))
    ->union($thirdTable->select('column1', 'column2'))
    ->get();


In the above example, we create instances of the Query Builder for each table and then use the union() method to combine the results of the three tables. Make sure that the columns selected for each table are the same so that the union operation can be performed.


You can add more tables to the union by calling the union() method with the Query Builder instance of the table you want to add.