1
0
Fork 0
internet-everythings-agricu.../app/Models/RegionCategory.php

63 lines
1.7 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Casts\Storage;
/**
* 区域分类
*/
class RegionCategory extends Model
{
use HasFactory;
use Filterable;
protected $fillable = ['name', 'icon', 'description', 'parent_id', 'level', 'sort', 'path', 'is_enable'];
protected $casts = [
'icon' => Storage::class,
];
protected function serializeDate(\DateTimeInterface $date){
return $date->format('Y-m-d H:i:s');
}
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');
}
public function scopeShow($q)
{
return $q->where('is_enable', 1);
}
public function scopeSort($q)
{
return $q->orderBy('sort', 'desc')->latest('id');
}
}