Ad

How To Make A Union Query Using Laravel Eloquent And Laravel Query Builder?

I am using laravel eloquent to CRUD data. My Problem is, I don't know how to make UNION queries using laravel Eloquent ORM. Can you help me to solve my problem?

This is my sample query that i want to implement in laravel Eloquent or Query Builder

SELECT in_records.item_id, 
       in_records.date, 
       in_records.value AS 'IN', 
       ''               AS 'OUT', 
       in_records.USER 
FROM   in_records 
UNION 
SELECT out_records.item_id, 
       out_records.date, 
       ''                AS 'IN', 
       out_records.value AS 'OUT', 
       out_records.USER 
FROM   out_records 
ORDER  BY date
Ad

Answer

$first= DB::table("in_records")
    ->select(" in_records.item_id,
        in_records.date,
        in_records.value AS 'IN',
        '' AS 'OUT',
        in_records.user");

$final= DB::table("out_records")
    ->select(" out_records.item_id,
         out_records.date,
         '' AS 'IN', 
         out_records.value AS 'OUT',
         out_records.user")
    ->union($first)
    ->get();

or maybe you can merge the results like this:

$a = Table::where('column','value')->get();
$b = Album::where('column','value')->get();
$result = $a->merge($b);
Ad
source: stackoverflow.com
Ad