我正在尝试使用其products_count显示所有类别。我正在雄辩地获取类别及其各自的product_count,没有任何问题。但是由于我的类别是嵌套的,所以我认为将其所有子类别的产品汇总为父类别product_count会很棒。
这是我的类别json输出
{
"id": 3,
"name_en": "Spices",
"parent_id": null,
"products_count": 0, // it should be 1 instead of 0
"children_count": 4,
"children": [
{
"id": 4,
"name_en": "HIJ",
"parent_id": 3,
"products_count": 0,
"children_count": 0,
"children": []
},
{
"id": 5,
"name_en": "XYZ",
"parent_id": 3,
"products_count": 1,
"children_count": 0,
"children": []
},
{
"id": 6,
"name_en": "ABC",
"parent_id": 3,
"products_count": 0,
"children_count": 0,
"children": []
},
{
"id": 7,
"name_en": "DEF",
"parent_id": 3,
"products_count": 0,
"children_count": 0,
"children": []
}
]
}
这是我的categoryController
...
public function index() {
return Category::whereNull('parent_id')
->with(['children' => function($category) {
return $category->withCount(['children', 'products']);
}])
->withCount(['children', 'products'])
->get()
}
...
CategoryModel
class CategoryModel extends Model {
public function parent() {
return $this->belongsTo('App\Category', 'id', 'parent_id');
}
public function children() {
return $this->hasMany('App\Category', 'parent_id', 'id')->with('children');
}
public function products() {
return $this->belongsToMany('App\Product')->withTimestamps();
}
}
产品型号
class Product extends Model
{
public function categories() {
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
编辑
category_product数据透视表有两列:
product_id | category_id
父类别与其子类别产品没有直接关系。是否可以通过雄辩的查询来完成此任务?当我探索一些类似的问题时,人们尝试使用递归关系进行尝试,有些人则尝试使用每个循环的手册,并通过循环父类别来添加子类别的产品计数。我认为这是一种昂贵的方法。必须有最佳的方法来做到这一点。请建议我什么是解决此问题的最佳方法。
在您的category :: modal中,您必须使用hasMany。产品属于类别。一个类别有很多产品。
public function products() {
return $this->hasMany('App\Product');
}
这将为您提供产品数->withCount('products')
[将我留在下面的评论中。