New-Thanasoft/thanasoft-back/app/Models/ProductCategory.php

84 lines
1.9 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ProductCategory extends Model
{
use HasFactory;
protected $fillable = [
'parent_id',
'code',
'name',
'description',
'intervention',
'active',
];
protected $casts = [
'active' => 'boolean',
'intervention' => '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');
}
/**
* Scope a query to only include active categories.
*/
public function scopeActive($query)
{
return $query->where('active', true);
}
/**
* Scope a query to only include root categories.
*/
public function scopeRoots($query)
{
return $query->whereNull('parent_id');
}
/**
* Check if the category has children.
*/
public function hasChildren(): bool
{
return $this->children()->exists();
}
/**
* Check if the category has products.
* Note: Assuming a Product model exists with a category_id or similar relationship.
* Since the migration for products might not be linked yet, this is a placeholder or checks a relation if defined.
* For now, I will assume a products relationship exists or will be added.
*/
public function products(): HasMany
{
return $this->hasMany(Product::class, 'categorie_id');
}
public function hasProducts(): bool
{
return $this->products()->exists();
}
}