owl-admin-base/app/Models/Keyword.php

77 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Admin\Components;
use Illuminate\Support\Facades\Str;
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::saving(function ($keyword) {
// 如果创建的是一个根类目
if (! $keyword->parent_id) {
// 将层级设为 1
$keyword->lv = 1;
// 将 path 设为 -
$keyword->path = '-';
if(empty($keyword->key)){
$keyword->key = Str::quickRandom($length = 16);
}
} else {
// 将层级设为父类目的层级 + 1
$keyword->lv = $keyword->parent->lv + 1;
$keyword->parent_key = $keyword->parent->key;
// 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符
$keyword->path = $keyword->parent->path.$keyword->parent_id.'-';
//当前key是否为空
if(empty($keyword->key)){
$keyword->key = $keyword->parent_key . '_' . (self::where('parent_key', $keyword->parent_key)->count() + 1);
}
}
});
}
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;
}
}