103 lines
2.0 KiB
PHP
103 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
|
|
class ProductCategory extends Model
|
|
{
|
|
protected $fillable = [
|
|
'parent_id',
|
|
'code',
|
|
'name',
|
|
'description',
|
|
'active',
|
|
];
|
|
|
|
protected $casts = [
|
|
'active' => 'boolean',
|
|
];
|
|
|
|
/**
|
|
* Get the parent category
|
|
*/
|
|
public function parent(): BelongsTo
|
|
{
|
|
return $this->belongsTo(ProductCategory::class, 'parent_id');
|
|
}
|
|
|
|
/**
|
|
* Get the child categories
|
|
*/
|
|
public function children(): HasMany
|
|
{
|
|
return $this->hasMany(ProductCategory::class, 'parent_id');
|
|
}
|
|
|
|
/**
|
|
* Get all products in this category
|
|
*/
|
|
public function products(): HasMany
|
|
{
|
|
return $this->hasMany(Product::class, 'categorie', 'name');
|
|
}
|
|
|
|
/**
|
|
* Get all descendant categories (recursive)
|
|
*/
|
|
public function descendants(): HasMany
|
|
{
|
|
return $this->children()->with('descendants');
|
|
}
|
|
|
|
/**
|
|
* Get the hierarchical path of the category
|
|
*/
|
|
public function getPathAttribute(): string
|
|
{
|
|
$path = $this->name;
|
|
$parent = $this->parent;
|
|
|
|
while ($parent) {
|
|
$path = $parent->name . ' > ' . $path;
|
|
$parent = $parent->parent;
|
|
}
|
|
|
|
return $path;
|
|
}
|
|
|
|
/**
|
|
* Scope to get only active categories
|
|
*/
|
|
public function scopeActive($query)
|
|
{
|
|
return $query->where('active', true);
|
|
}
|
|
|
|
/**
|
|
* Scope to get root categories (no parent)
|
|
*/
|
|
public function scopeRoots($query)
|
|
{
|
|
return $query->whereNull('parent_id');
|
|
}
|
|
|
|
/**
|
|
* Check if category has children
|
|
*/
|
|
public function hasChildren(): bool
|
|
{
|
|
return $this->children()->exists();
|
|
}
|
|
|
|
/**
|
|
* Check if category has products
|
|
*/
|
|
public function hasProducts(): bool
|
|
{
|
|
return $this->products()->exists();
|
|
}
|
|
}
|