【问题标题】:How do I write an eloquent query which joins, merges or unions these 2 queries into 1?如何编写一个雄辩的查询,将这 2 个查询连接、合并或联合为 1?
【发布时间】:2020-02-17 04:55:25
【问题描述】:

// 2 eloqent collections 合并

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

// 上面的这个查询执行了这两个重复的 MySQL 查询。

此结果是正确的,但是需要 2 次查询。
如何编写一个雄辩的查询,将这 2 个查询连接、合并或联合为 1 个?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    为什么要单独获取?您可以为此使用Orwhere

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

    更新

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

    这样,您将获得两个(公共或私人)类别。

    【讨论】:

    • 谢谢,我去看看。
    • 这个答案是正确的。最重要的是,我建议你看看Query Optimisationstackoverflow.com/a/60015685/5326191
    • Query Optimisation非常有帮助,我很感激。
    • 我必须添加 ->where('id', '!=', 2)。因为前面的查询是 2 个单独的查询。如何使用 eloquent 进行子查询?
    • 检查更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多