Elio Chamy
Elio Chamy

Reputation: 269

Laravel unnioAll between multi queries

I have 3 queries in my laravel controller:

$data1=DB::table('tabl1')->where('brandid',$brandid)
                     ->select('id', 'name', DB::raw('sum(amount) AS SUM'))
                     ->get();

$data2=DB::table('tabl2')->where('brandid',$brandid)
                     ->select('id', 'name', DB::raw('sum(tax) AS SUM'))
                     ->get();

$data3=DB::table('tabl3')->where('brandid',$brandid)
                     ->select('id', 'name', DB::raw('sum(tax2) AS SUM'))
                     ->get();

I want to select the id, name and the sum of the 3 SUM using union between the 3 tables. I give up, any idea?

Upvotes: 1

Views: 35

Answers (1)

KuKeC
KuKeC

Reputation: 4610

You can do it like this

$data1=DB::table('tabl1')->where('brandid',$brandid)
                     ->select('id', 'name', DB::raw('sum(amount) AS SUM'));

$data2=DB::table('tabl2')->where('brandid',$brandid)
                     ->select('id', 'name', DB::raw('sum(tax) AS SUM'));

$data3=DB::table('tabl3')->where('brandid',$brandid)
                     ->select('id', 'name', DB::raw('sum(tax2) AS SUM'));

$data = $data1->unionAll($data2)->unionAll($data3);
$data = $data->get();

Didn't tested it but i think it should work

Upvotes: 1

Related Questions