86 lines
2.5 KiB
PHP
86 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace Peidikeji\Goods\Models;
|
|
|
|
use Dcat\Admin\Traits\ModelTree;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class GoodsCategory extends Model
|
|
{
|
|
use ModelTree;
|
|
|
|
protected $table = 'goods_category';
|
|
|
|
protected $fillable = ['name', 'image', 'description', 'parent_id', 'level', 'sort', 'path', 'is_enable'];
|
|
|
|
protected $titleColumn = 'name';
|
|
protected $orderColumn = 'sort';
|
|
|
|
public $timestamps = false;
|
|
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
// 监听 Category 的创建事件,用于初始化 path 和 level 字段值
|
|
static::creating(function ($category) {
|
|
// 如果创建的是一个根类目
|
|
if (!$category->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');
|
|
}
|
|
}
|