bhdrnzl
bhdrnzl

Reputation: 61

Laravel join and unionAll

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();

Upvotes: 3

Views: 13637

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

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()

Upvotes: 6

Related Questions