Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union with unequal number of columns in Laravel

I would like to know how it's possible to make a union/union all query using tables with unequal number of columns (say 3 and 4). I know that I can achieve this using NULL AS col in simple SQL.

However I am working in Laravel and I would like to know whether there is a possible way of doing this using Query/Builder or any other way.

like image 811
csdinos Avatar asked Jul 11 '16 12:07

csdinos


1 Answers

This worked for me, with sql query builder of laravel 5.2

        $first = DB::table('user_prod')
            ->select('user_id', DB::raw("NULL as debit")) //shows 'null' because the 'debit' column does not exist in this table
            ->where('user_id', '=', Auth::user()->id);

        $second = DB::table('user_transaction')
            ->select('user_id', DB::raw("debit")) //shows the value of the column 'debit' table 'user_transaction'
            ->where('user_id', '=', Auth::user()->id)

            ->union($first)
            ->get();

dd($second);

like image 84
Hergy Avatar answered Sep 18 '22 01:09

Hergy