2

// 2 eloqent collections merged

$publicCategories = Category::where('menu', '=', 1)
    ->where('display_scope', 1)
    ->orderBy('parent_id')
    ->get();
$privateCategories = Category::where('menu', '=', 1)
    ->whereIn('id', $ids)
    ->orderBy('parent_id')
    ->get();
$categories = $publicCategories->merge($privateCategories);

// This query above does these 2 MySQL queries which are duplicated.

enter image description here

The result from this is correct, however, requires 2 queries.
How do I write an eloquent query which joins, merges or unions these 2 queries into 1?

Moshiur
  • 659
  • 6
  • 22
Josh
  • 305
  • 4
  • 15

1 Answers1

2

Why you're getting it separately? You can use Orwhere for this.

$publicprivateCategories = Category::where('menu', '=', 1)
                        ->whereIn('id', $ids)
                        ->orWhere('display_scope', 1)
                        ->orderBy('parent_id')
                        ->get();

Update

$publicprivateCategories = Category::where('menu', '=', 1)
                        ->where(function($q) use($ids){
                             $q->whereIn('id', $ids)->orWhere('display_scope', 1);
                        })
                        ->where('id', '!=', 2)
                        ->orderBy('parent_id')
                        ->get();

By this, you'll get both(Public or private) categories.

Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49