refactor: 产品分类添加path层级路径逻辑

This commit is contained in:
2025-04-24 14:21:33 +08:00
parent 865193475b
commit 8e7bb8c51a
4 changed files with 22 additions and 17 deletions

View File

@@ -98,6 +98,9 @@ class ProductCategory
if ($data['pid'] > 0) {
$parent = $category->bypk($data['pid'])->find();
if (!empty($parent)) {
if (!empty($parent->path)) {
$data['path'] = $parent->path . ',' . $parent->id;
}
$data['level'] = $parent->level + 1;
}
}
@@ -145,6 +148,10 @@ class ProductCategory
if ($data['pid'] != $category->pid) {
$parent = ProductCategoryModel::bypk($data['pid'])->find();
if (!empty($parent)) {
$data['path'] = $parent->id;
if (!empty($parent->path)) {
$data['path'] = $parent->path . ',' . $data['path'];
}
$data['level'] = $parent->level + 1;
$updated_level = true;
}
@@ -156,21 +163,24 @@ class ProductCategory
// 处理子分类层级
if ($updated_level) {
$this->handle_children($category->id, $data['level']);
$this->handle_children($category->id, $data['path'], $data['level']);
}
return success('操作成功');
}
private function handle_children($pid, $level)
private function handle_children($pid, $path, $level)
{
$children = ProductCategoryModel::pid($pid)->select();
if ($children->isEmpty()) {
return;
}
foreach ($children as $child) {
if (!empty($path)) {
$child->path = $path. ','. $child->pid;
}
$child->level = $level + 1;
if ($child->save()) {
$this->handle_children($child->id, $child->level);
$this->handle_children($child->id, $child->path, $child->level);
}
}
}