42 lines
1.2 KiB
PHP
42 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use EloquentFilter\Filterable;
|
|
|
|
class RegionCategory extends Model
|
|
{
|
|
use HasFactory;
|
|
use Filterable;
|
|
|
|
protected $fillable = ['name', 'icon', 'description', 'parent_id', 'level', 'sort', 'path', 'is_enable'];
|
|
|
|
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
// 监听 Category 的创建事件,用于初始化 path 和 level 字段值
|
|
static::creating(function ($category) {
|
|
// 如果创建的是一个根类目
|
|
if (! $category->parent_id) {
|
|
// 将层级设为 1
|
|
$category->level = 1;
|
|
// 将 path 设为 -
|
|
$category->path = '-';
|
|
} else {
|
|
// 将层级设为父类目的层级 + 1
|
|
$category->level = $category->parent->level + 1;
|
|
// 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符
|
|
$category->path = $category->parent->path.$category->parent_id.'-';
|
|
}
|
|
});
|
|
}
|
|
|
|
public function parent()
|
|
{
|
|
return $this->belongsTo(self::class, 'parent_id');
|
|
}
|
|
}
|