我正尝试使用其products_count显示所有类别。我正在雄辩地获取类别及其各自的product_count,没有任何问题。但是由于我的类别是嵌套的,所以我认为将所有子类别的产品都归为父类别products_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();
}
}
ProductModel
class Product extends Model
{
public function categories() {
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
编辑
category_product 数据透视表具有两列:
product_id | category_id
父类别与其子类别产品没有直接关系。是否可以通过雄辩的查询来完成此任务?当我探索一些类似的问题时,人们尝试使用递归关系进行尝试,而有些人则尝试使用每个循环的手册,并通过循环父类别来添加子类别的产品计数。我认为这是一种昂贵的方法。必须有最佳的方法来做到这一点。请建议我什么是解决此问题的最佳方法。
答案 0 :(得分:1)
在您的category :: modal中,您必须使用 hasMany 。产品属于类别。一个类别有很多产品。
public function products() {
return $this->hasMany('App\Product');
}
这将为您提供产品数量->withCount('products')
让我在下面的评论中发帖。
答案 1 :(得分:0)
您可以使用子选择
$categories = Category::with('children')
->selectRaw('( SELECT COUNT(*) FROM `products` WHERE products.category_id IN (SELECT C.id from categories as C WHERE c.parent_id = categories.id) ) AS `product_count`')
->get();