How do I write an eloquent query which joins, merges or unions these 2 queries into 1?

Josh :

// 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?

Dilip Hirapara :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11858&siteId=1