parent_id) { // 将层级设为 1 $category->level = 1; // 将 path 设为 - $category->path = '-'; } else { // 将层级设为父类目的层级 + 1 $category->level = $category->parent->level + 1; // 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符 $category->path = $category->parent->path.$category->parent_id.'-'; } }); static::deleting(function ($category) { // 所有下级分类 $ids = GoodsCategory::where('path', 'like', '%-'.$category->id.'-%')->pluck('id'); // 检查下级分类是否包含商品 if (Goods::whereIn('category_id', array_merge($ids, [$category->id]))->exists()) { // todo 阻止删除该分类 } // 删除所有下级分类 GoodsCategory::where('path', 'like', '%-'.$category->id.'-%')->delete(); }); } public static function selectOptions(\Closure $closure = null, $rootText = null) { $options = (new static())->withQuery($closure)->buildSelectOptions(); $list = collect($options); if ($rootText !== false) { $rootText = $rootText ?: admin_trans_label('root'); $list->prepend($rootText, 0); } return $list->all(); } public function parent() { return $this->belongsTo(self::class, 'parent_id'); } public function children() { return $this->hasMany(self::class, 'parent_id'); } public function goods() { return $this->hasMany(Goods::class, 'category_id'); } public function scopeOrder($q) { return $q->orderBy('sort'); } }