php - 拉维尔 5.4 : count the products in each category and sort them by Eloquent query

标签 php laravel eloquent

我有两个模型,一个是Product,另一个是ProductCategory

我和两者之间有关系

产品型号

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

产品类别模型

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

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

我需要一个 Eloquent 查询,它将获得 4 个类别,这些类别按每个类别中的产品数量排序。

例如

cat-2 has 7 products
cat-3 has 5 products
cat-1 has 3 products

谢谢

最佳答案

使用withCount()然后 orderBy()单个查询来实现。

ProductCategory::with('categoryProduct')->withCount('categoryProduct')->orderBy('category_product_count','desc')->get();

为了得到计数

ProductCategory::withCount('categoryProduct')->orderBy('category_product_count','desc')->get();

关于php - 拉维尔 5.4 : count the products in each category and sort them by Eloquent query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49627696/

相关文章:

php - 当两个表中具有相同的列名时获取正确的值 - 基于选择中的最大值

php - 如何用php自动完成mysql数据库?

自升级到 5.5 以来,Laravel Forge/Envoyer 使用旧版本

php - 如何在 Laravel 5.4 中验证文件名

php - 从 WP_List_Table 代码处理 Wordpress 中的搜索

php - 最佳实践 : Tracking Banner Impressions

php - Laravel 更改器(mutator)从 JSON 到 php 数组以显示在数据表中

Laravel eloquent中的Mysql按查询求和分组

laravel - 有条件的热切加载-Laravel

php - 从 Laravel 中的关系中检索关系