Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel join and unionAll

Tags:

php

laravel

I have a database query. It's already working now, but I'm trying to add the unionAll method to this query, I did not do it. I want to combine the two tables with the unionAll method.

    $uid = Auth::id();

    $homeCovering = DB::table('bid_requests')
        ->leftJoin('bid_home_coverings', 'bid_requests.id', '=', 'bid_home_coverings.bidId')
        ->where('bid_requests.userId', '=', $uid)
        ->where('district', '!=', null)
        ->get();

    $vehicleCovering = DB::table('bid_requests')
        ->leftJoin('bid_vehicle_coverings', 'bid_requests.id', '=', 'bid_vehicle_coverings.bidId')
        ->where('bid_requests.userId', $uid)
        ->where('district', '!=', null)
        ->get();
like image 703
bhdrnzl Avatar asked Dec 03 '25 10:12

bhdrnzl


1 Answers

Use unionAll() method, Also make sure you really need union all, there is a difference between union and union all

$homeCovering = DB::table('bid_requests')
    ->select('bid_requests.*')
    ->leftJoin('bid_home_coverings', 'bid_requests.id', '=', 'bid_home_coverings.bidId')
    ->where('bid_requests.userId', '=', $uid)
    ->where('district', '!=', null);

$bid_requests = DB::table('bid_requests')
    ->select('bid_requests.*')
    ->leftJoin('bid_vehicle_coverings', 'bid_requests.id', '=', 'bid_vehicle_coverings.bidId')
    ->where('bid_requests.userId', $uid)
    ->unionAll($homeCovering)
    ->where('district', '!=', null)
    ->get();

Or you could merge these queries as a single query

$bid_requests = DB::table('bid_requests')
    ->select('bid_requests.*')
    ->leftJoin('bid_vehicle_coverings', 'bid_requests.id', '=', 'bid_vehicle_coverings.bidId')
    ->leftJoin('bid_home_coverings', 'bid_requests.id', '=', 'bid_home_coverings.bidId')
    ->where('bid_requests.userId', $uid)
    ->where('district', '!=', null)
    ->get();

If you need distinct bid requests add ->distinct()

like image 199
M Khalid Junaid Avatar answered Dec 05 '25 00:12

M Khalid Junaid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!