69 lines
2.0 KiB
PHP
69 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use EloquentFilter\Filterable;
|
|
use App\Admin\Components;
|
|
|
|
class Keyword extends Model
|
|
{
|
|
use HasFactory;
|
|
use Filterable;
|
|
|
|
protected $fillable = ['name', 'key', 'value', 'parent_id', 'parent_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->parent_key = $keyword->parent->key;
|
|
// 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符
|
|
$keyword->path = $keyword->parent->path.$keyword->parent_id.'-';
|
|
}
|
|
});
|
|
}
|
|
|
|
public function parent()
|
|
{
|
|
return $this->belongsTo(static::class, 'parent_id');
|
|
}
|
|
|
|
public function children()
|
|
{
|
|
return $this->hasMany(static::class, 'parent_id');
|
|
}
|
|
|
|
public function scopeAllChildrenOfKey($q, $parentKey)
|
|
{
|
|
$q->where('path','like', '%-'.
|
|
static::where('key', $parentKey)->value('id')
|
|
. '-%' ?? '');
|
|
}
|
|
|
|
public static function tagsMap(String $key)
|
|
{
|
|
$mapArr = [];
|
|
self::query()->where('parent_key', $key)->get()->map(function($item) use (&$mapArr){
|
|
$mapArr[$item->id] = Components::make()->keywordsTag($item->name, $item->value);
|
|
});
|
|
return $mapArr;
|
|
}
|
|
}
|