laravel query optimization usng union and intersection code example

Example 1: laravel query optimization usng union and intersection

$silver = DB::table("product_silver")    ->select("product_silver.name"      ,"product_silver.price"      ,"product_silver.quantity");  $gold = DB::table("product_gold")    ->select("product_gold.name"      ,"product_gold.price"      ,"product_gold.quantity")    ->union($silver)    ->get();  dd($gold);

Example 2: how to use union and intersection in laravel query

$queryWithParent = SaleService::query()
    ->select(\DB::raw('DISTINCT ON (properties.parent_id) sale_services.*'))
    ->from('sale_services')
    ->join('properties', 'sale_services.property_id', '=', 'properties.id')
    ->whereNotNull('properties.parent_id')
    ->orderBy('properties.parent_id')
    ->orderBy('sale_services.index_range', 'desc');

$queryWithoutParent = SaleService::query()
    ->select(\DB::raw('sale_services.*'))
    ->join('properties', 'sale_services.property_id', '=', 'properties.id')
    ->whereNull('properties.parent_id');

$query = $queryWithParent->union($queryWithoutParent);

Tags:

Misc Example