Based on your answer you can remove the extra queries in the loop, at the least:
$children = $category->children()->withCount('products')->get();
return $children->sum('products_count');
Or you can do the actual query from the inverse direction and remove the need for all of this:
return Product::whereHas('child.category', function ($q) {
$q->where('slug', 'shirts');
})->count();
Though, I don't know how you setup these relationships in the inverse.
Based on the relationships you have you probably need to do more querying here as I would suppose a Product could belong to a parent or child category:
return Product::whereHas('category', function ($q) {
$q->where('slug', 'shirts')
->orWhereHas('parent', fn ($q) => $q->where('slug', 'shirts'));
})->count();
The Product
model should have a category
relationship (belongsTo
). The parent
relationship on Category
should be a belongsTo
not hasOne
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…