gpt4 book ai didi

php - 如何编写一个 Eloquent 查询,将这 2 个查询连接、合并或联合为 1?

转载 作者:行者123 更新时间:2023-12-04 10:34:24 24 4
gpt4 key购买 nike

//2 个 eloqent 集合合并

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

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

enter image description here

结果是正确的,但是需要 2 次查询。
如何编写一个 Eloquent 查询,将这 2 个查询连接、合并或联合为 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();

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

关于php - 如何编写一个 Eloquent 查询,将这 2 个查询连接、合并或联合为 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60256129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com