feat: Implement full CRUD API for product categories and products, including recursive product counts for categories.
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user