简体   繁体   中英

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

Use

 $res = DB::select("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");
$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM