Laravel 5.4:统计每个类别中的产品并通过 Eloquent 查询对其进行排序

You*_*taf 2 php laravel laravel-eloquent

我有两个,Models一个是Product,另一个是ProductCategory

我和两者之间都有关系

产品型号

public function productCategory() {
        return $this->belongsTo( ProductCategory::class, 'product_category_id' );
    }
Run Code Online (Sandbox Code Playgroud)

产品类别型号

public function categoryProduct() {
        return $this->hasMany( Product::class, 'product_category_id' );
    }
Run Code Online (Sandbox Code Playgroud)

现在每个类别都有一些产品,例如(cat-1 has 3 products, cat-2 has 7 products, cat-3 has 5 products)

我需要一个Eloquent query将按每个类别中的产品数量排序的 4 个类别。

对于前。

cat-2 has 7 products
cat-3 has 5 products
cat-1 has 3 products
Run Code Online (Sandbox Code Playgroud)

任务

Soh*_*415 6

使用withCount()然后orderBy()使其与single查询。

ProductCategory::with('categoryProduct')->withCount('categoryProduct')->orderBy('category_product_count','desc')->get();
Run Code Online (Sandbox Code Playgroud)

只得到计数

ProductCategory::withCount('categoryProduct')->orderBy('category_product_count','desc')->get();
Run Code Online (Sandbox Code Playgroud)