feat: Implement full CRUD API for product categories and products, including recursive product counts for categories.

This commit is contained in:
pbao9
2026-03-06 11:15:26 +07:00
parent cca4e0b86f
commit cb8510cf56
5 changed files with 302 additions and 1 deletions
+20 -1
View File
@@ -29,7 +29,9 @@ class ProductCategories extends Model
public function children()
{
return $this->hasMany(ProductCategories::class, 'parent_id')->with('children');
return $this->hasMany(ProductCategories::class, 'parent_id')
->withCount('products')
->with('children');
}
public function products()
@@ -37,6 +39,23 @@ class ProductCategories extends Model
return $this->hasMany(Product::class, 'product_categories_id');
}
/**
* Recursively count products in this category and all descendants.
* Requires `withCount('products')` and `with('children')` to be loaded.
*/
public function getRecursiveProductsCountAttribute(): int
{
$count = (int) ($this->products_count ?? 0);
if ($this->relationLoaded('children')) {
foreach ($this->children as $child) {
$count += $child->recursive_products_count;
}
}
return $count;
}
public function getTypeLabelAttribute(): ?string
{
if (!$this->type) {