如何使用左连接进行选择,其中一个表的计数大于1?

huangapple go评论49阅读模式
英文:

how to SELECT with left join where count of one table is more than 1?

问题

以下是翻译好的部分:

我已经实现了类似这样的查询:

$categories = DB::select("SELECT categories.* FROM categories left JOIN products on products.category_root = categories.id")
                    ->withCount('products')
                    ->where('products_count', '>', 0)
                    ->get();

这意味着获取至少有一个具有与category->id相等的category_root的产品的类别。

我的产品表有3个列的名称:category_rootcategory_parentcategory_id,我想在我的集合中检查它们的每一个。

如何获取非空的类别?

英文:

I have implemented a query like this :

$categories = DB::select("SELECT categories.* FROM categories left JOIN products on products.category_root = categories.id")
                ->withCount('products')
                ->where('products_count' , '>' , 0)->get();

that mean get categories where have at least one product with category_root equal the category->id

my products table have 3 column with names : category_root , category_parent , category_id
and I want to check each of them in my collections.

how to get not empty categories ?

答案1

得分: 1

$categories = Category::whereExists(function ($query) {
$query->select(DB::raw(1))->from('products')->whereRaw('products.category_root = categories.id');
})->get();

英文:

try

$categories = Category::whereExists(function ($query){
            $query->select(DB::raw(1))->from('products')->whereRaw('products.category_root = categories.id');
        })->get();

答案2

得分: 0

使用 leftJoin() 方法,您可以在闭包中添加您的条件:

$categories = DB::table('categories')
                ->leftJoin('products', function ($join) {
                    $join->on('categories.id', '=', 'products.category_root')
                         ->orWhere('categories.id', '=', 'products.category_parent')
                         ->orWhere('categories.id', '=', 'products.category_id');
                })
                ->select('categories.*')
                ->whereNotNull('products.id')
                ->withCount('products')
                ->get();
英文:

Using leftJoin() method, You can add your condition in the closure:

$categories = DB::table('categories')
                ->leftJoin('products', function ($join) {
                    $join->on('categories.id', '=', 'products.category_root')
                         ->orWhere('categories.id', '=', 'products.category_parent')
                         ->orWhere('categories.id', '=', 'products.category_id');
                })
                ->select('categories.*')
                ->whereNotNull('products.id')
                ->withCount('products')
                ->get();

huangapple
  • 本文由 发表于 2023年4月10日 20:24:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定