diff --git a/app/Models/Keyword.php b/app/Models/Keyword.php index e94bffd..f0b7242 100644 --- a/app/Models/Keyword.php +++ b/app/Models/Keyword.php @@ -21,4 +21,35 @@ class Keyword extends Model 'options' => 'array', 'image' => StorageFile::class, ]; + + protected static function booted(): void + { + static::creating(function (Model $model) { + if ($model->parent_id) { + $parent = static::query()->findOrFail($model->parent_id); + $model->path = $parent->path . $parent->id . '-'; + $model->level = $parent->level + 1; + } else { + $model->parent_id = 0; + $model->path = '-'; + $model->level = 1; + } + }); + + static::updating(function (Model $model) { + if ($model->parent_id) { + $parent = static::query()->findOrFail($model->parent_id); + $model->path = $parent->path . $parent->id . '-'; + $model->level = $parent->level + 1; + } else { + $model->parent_id = 0; + $model->path = '-'; + $model->level = 1; + } + }); + + static::deleting(function (Model $model) { + static::query()->allChildren($model->id)->delete(); + }); + } }