refactor: 修改产品分类父级不为自身或子分类
This commit is contained in:
@@ -82,7 +82,7 @@ class ProductCategory
|
||||
$data = array_merge($post, ['language_id' => request()->lang_id]);
|
||||
|
||||
$validate = new ProductCategoryValidate;
|
||||
if (!$validate->check($data)) {
|
||||
if (!$validate->scene('add')->check($data)) {
|
||||
return error($validate->getError());
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ declare (strict_types = 1);
|
||||
|
||||
namespace app\admin\validate\v1;
|
||||
|
||||
use app\admin\model\v1\ProductCategoryModel;
|
||||
use think\facade\Db;
|
||||
use think\Validate;
|
||||
|
||||
class ProductCategoryValidate extends Validate
|
||||
@@ -14,8 +16,10 @@ class ProductCategoryValidate extends Validate
|
||||
* @var array
|
||||
*/
|
||||
protected $rule = [
|
||||
'id' => 'require|integer',
|
||||
'language_id' => 'require|integer',
|
||||
'unique_id' => 'require',
|
||||
'pid' => 'integer|different:id|checkPidNotBeChildren',
|
||||
'name' => 'require|max:64',
|
||||
'icon' => 'max:125',
|
||||
'desc' => 'max:255',
|
||||
@@ -35,9 +39,14 @@ class ProductCategoryValidate extends Validate
|
||||
* @var array
|
||||
*/
|
||||
protected $message = [
|
||||
'id.require' => 'ID不能为空',
|
||||
'id.integer' => 'ID必须为整数',
|
||||
'language_id.require' => '语言ID不能为空',
|
||||
'language_id.integer' => '语言ID必须为整数',
|
||||
'unique_id.require' => '唯一标识不能为空',
|
||||
'pid.different' => '父级ID不能为自身',
|
||||
'pid.checkPidNotBeChildren' => '父级ID不能为自身的子分类',
|
||||
'pid.integer' => '父级ID必须为整数',
|
||||
'name.require' => '名称不能为空',
|
||||
'name.max' => '名称最多不能超过64个字符',
|
||||
'icon.max' => '图标最多不能超过125个字符',
|
||||
@@ -50,4 +59,36 @@ class ProductCategoryValidate extends Validate
|
||||
'seo_keywords.max' => 'SEO关键字最多不能超过255个字符',
|
||||
'seo_desc.max' => 'SEO描述最多不能超过255个字符',
|
||||
];
|
||||
|
||||
// 验证pid
|
||||
protected function checkPidNotBeChildren($value, $rule, $data = [])
|
||||
{
|
||||
if ($value == 0) {
|
||||
return true;
|
||||
}
|
||||
$table_name = (new ProductCategoryModel)->getTable();
|
||||
$children = Db::query(
|
||||
preg_replace(
|
||||
'/\s+/u',
|
||||
' ',
|
||||
"WITH RECURSIVE tree_by AS (
|
||||
SELECT a.id, a.pid FROM $table_name a WHERE a.id = {$data['id']}
|
||||
UNION ALL
|
||||
SELECT k.id, k.pid FROM $table_name k INNER JOIN tree_by t ON t.id = k.pid
|
||||
)
|
||||
SELECT id FROM tree_by WHERE id <> {$data['id']};"
|
||||
)
|
||||
);
|
||||
if (!empty($children) && in_array($data['pid'], array_column($children, 'id'))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// 新增场景
|
||||
public function sceneAdd()
|
||||
{
|
||||
return $this->remove('id', 'require|integer')->remove('pid', 'different|checkPidNotBeChildren');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user