如何在Laravel中使用Eloquent ORM统计并展示分类下的商品数量
步骤1:定义模型关联
首先在App\Models\Category模型中添加和商品的一对多关联:
// App\Models\Category.php public function products() { return $this->hasMany(Product::class, 'categoryId', 'id'); }
如果需要只统计启用状态的商品,可以在关联里加条件:
public function activeProducts() { return $this->hasMany(Product::class, 'categoryId', 'id')->where('status', 1); }
对应的App\Models\Product模型中添加属于分类的关联:
// App\Models\Product.php public function category() { return $this->belongsTo(Category::class, 'categoryId', 'id'); }
步骤2:使用withCount统计商品数量
查询分类数据时使用withCount方法即可直接得到关联商品的统计值,默认会生成{关联名}_count字段:
// 查询所有启用的分类,同时统计每个分类下启用的商品数量 $categories = Category::where('status', 1) ->withCount('activeProducts') // 如果你用的是普通products关联就写withCount('products') ->get();
步骤3:前端遍历展示
在Blade模板中遍历输出即可得到你要的效果:
<ol> @foreach($categories as $category) <li>{{ $category->categoryName }} ({{ $category->active_products_count }})</li> @endforeach </ol>
输出示例:
- Fruits & Vegetables (5)
- Fresh Fruits (2)
- Breakfast (3)
可选:统计子分类商品汇总
如果你的分类是多级树形结构,需要统计当前分类+所有子分类的商品总数,可以自己定义一个访问器递归统计,常用的代码示例如下:
// 在Category模型中添加访问器 public function getTotalProductsCountAttribute() { $count = $this->active_products_count; foreach ($this->children as $child) { $count += $child->total_products_count; } return $count; } // 记得先定义子分类关联 public function children() { return $this->hasMany(Category::class, 'parentId', 'id')->with('children'); }
使用时直接调用$category->total_products_count即可得到包含子分类的总商品数。
内容的提问来源于stack exchange,提问作者Md. Shiam Hossain
相关产品推荐
相关产品推荐

