51 lines
1.4 KiB
PHP
51 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use EloquentFilter\Filterable;
|
|
|
|
class Keyword extends Model
|
|
{
|
|
use HasFactory;
|
|
use Filterable;
|
|
|
|
protected $fillable = ['name', 'key', 'value', 'p_id', 'p_key', 'path', 'sort', 'lv'];
|
|
|
|
protected function serializeDate(\DateTimeInterface $date){
|
|
return $date->format('Y-m-d H:i:s');
|
|
}
|
|
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
// 监听 Keyword 的创建事件,用于初始化 path 和 lv 字段值
|
|
static::creating(function ($keyword) {
|
|
// 如果创建的是一个根类目
|
|
if (! $keyword->parent_id) {
|
|
// 将层级设为 1
|
|
$keyword->lv = 1;
|
|
// 将 path 设为 -
|
|
$keyword->path = '-';
|
|
} else {
|
|
// 将层级设为父类目的层级 + 1
|
|
$keyword->lv = $keyword->parent->lv ++;
|
|
$keyword->p_key = $keyword->parent->key;
|
|
// 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符
|
|
$keyword->path = $keyword->parent->path.$keyword->p_id.'-';
|
|
}
|
|
});
|
|
}
|
|
|
|
public function parent()
|
|
{
|
|
return $this->belongsTo(static::class, 'p_id');
|
|
}
|
|
|
|
public function children()
|
|
{
|
|
return $this->hasMany(static::class, 'p_id');
|
|
}
|
|
}
|