65 lines
1.9 KiB
PHP
65 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use EloquentFilter\Filterable;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use App\Admin\Components;
|
|
|
|
class Keyword extends Model
|
|
{
|
|
use HasFactory;
|
|
use Filterable;
|
|
|
|
protected $fillable = ['name', 'key', 'value', 'parent_id', 'type_key', 'path', 'sort', 'level'];
|
|
|
|
protected function serializeDate(\DateTimeInterface $date){
|
|
return $date->format('Y-m-d H:i:s');
|
|
}
|
|
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
// 监听 Keyword 的创建事件,用于初始化 path 和 level 字段值
|
|
static::creating(function ($keyword) {
|
|
// 如果创建的是一个根类目
|
|
if (! $keyword->parent_id) {
|
|
// 将层级设为 1
|
|
$keyword->level = 1;
|
|
// 将 path 设为 -
|
|
$keyword->path = '-';
|
|
} else {
|
|
// 将层级设为父类目的层级 + 1
|
|
$keyword->level = $keyword->parent->level + 1;
|
|
$keyword->type_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 static function getByParentKey(String $key)
|
|
{
|
|
return self::query()->where('type_key', $key)->get();
|
|
}
|
|
|
|
public static function tagsMap(String $key){
|
|
$list = self::query()->where('type_key', $key)->get()->pluck('name', 'id')->toArray();
|
|
return array_map(function($item){
|
|
return Components::make()->keywordsTag($item);
|
|
}, $list);
|
|
}
|
|
}
|