You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.4:用Eloquent查询统计各分类产品数并排序

解决方案:统计产品分类的产品数量并排序

嘿,我来帮你搞定这个统计排序的需求!既然你已经在Product和ProductCategory模型间建立好了关联,那用Laravel的Eloquent来实现这个需求其实非常简单,下面给你几种实用的方案:

1. 最简洁的方案:使用withCount

Laravel Eloquent提供了专门的withCount方法来统计关联模型的数量,这是最推荐的方式,代码简洁且性能高效:

// 统计每个分类的产品数量,并按数量降序排序(从多到少)
$categories = ProductCategory::withCount('categoryProduct')
    ->orderBy('category_product_count', 'desc')
    ->get();

// 如果需要升序排序(从少到多),把desc改成asc即可
// $categories = ProductCategory::withCount('categoryProduct')
//     ->orderBy('category_product_count', 'asc')
//     ->get();

说明:

  • withCount('categoryProduct')会自动为每个ProductCategory模型添加一个名为category_product_count的属性,存储该分类下的产品总数。
  • 直接通过这个自动生成的字段进行排序就可以了,不需要额外的子查询或分组操作。

扩展:带条件的统计

如果需要统计满足特定条件的产品(比如只统计上架的产品),可以给withCount传入闭包来过滤:

$categories = ProductCategory::withCount([
    'categoryProduct' => function ($query) {
        // 假设你的Product模型有is_active字段标识是否上架
        $query->where('is_active', 1);
    }
])
->orderBy('category_product_count', 'desc')
->get();

2. 备选方案:使用关联查询+分组统计

如果你需要更自定义的查询逻辑,也可以通过左连接+分组的方式实现:

use Illuminate\Support\Facades\DB;

$categories = ProductCategory::select('product_categories.*', DB::raw('count(products.id) as product_count'))
    ->leftJoin('products', 'product_categories.id', '=', 'products.product_category_id')
    ->groupBy('product_categories.id')
    ->orderBy('product_count', 'desc')
    ->get();

说明:

  • 这里通过leftJoin关联产品表,确保即使某个分类没有产品也会被统计到(数量为0)。
  • 使用DB::raw来生成统计字段product_count,然后按这个字段排序。
  • 注意:如果你的Laravel开启了严格模式,可能需要在config/database.php中调整mysql配置的strict选项,或者确保groupBy包含所有需要查询的字段(不过一般只分组分类ID就够了)。

使用示例

获取到结果后,你可以在视图或者逻辑中直接使用统计值:

{{-- 示例:在Blade视图中输出 --}}
@foreach($categories as $category)
    <div>
        <h3>{{ $category->name }}</h3>
        <p>产品数量:{{ $category->category_product_count }}</p> {{-- 对应withCount的方案 --}}
        {{-- <p>产品数量:{{ $category->product_count }}</p> --}} {{-- 对应分组查询的方案 --}}
    </div>
@endforeach

内容的提问来源于stack exchange,提问作者Yousef Altaf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:11:16