Browse Source

分类下如果发布有产品,不允许删除分类

dev
李可松 4 years ago
parent
commit
5806108a16
  1. 28
      app/Admin/Controllers/CategoryController.php
  2. 25
      app/AdminAgent/Controllers/CategoryController.php

28
app/Admin/Controllers/CategoryController.php

@ -3,6 +3,8 @@
namespace App\Admin\Controllers;
use App\Models\Category;
use App\Models\Product;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
@ -82,6 +84,30 @@ class CategoryController extends AdminController
//后台管理员的agent_id为0
$form->agent_id = 0;
$form->sort = $form->sort ?? 255;
});
})->deleting(function (Form $form) {
//获取到要删除分类的ID
$category_id = (int)$form->getKey();
//获取要删除类目的所有下级ID
$category = Category::where('agent_id', 0)->pluck('pid', 'id')->toArray();
$ids = getChildCate($category_id, $category);
if (Product::query()->whereIn('category_id', $ids)->exists()) {
return $form->response()->error('该分类下已经发布产品,不允许删除');
}
return $form->response()->error('不允许删除');
});
}
}
//获取$pid下的所有子类目
function getChildCate($pid, $category): array
{
$cate_arr = [$pid];
foreach ($category as $k => $v) {
if ($v == $pid) {
$cate_arr = array_merge($cate_arr, getChildCate($k, $category));
}
}
return $cate_arr;
}

25
app/AdminAgent/Controllers/CategoryController.php

@ -2,6 +2,7 @@
namespace App\AdminAgent\Controllers;
use App\Models\AgentProduct;
use App\Models\Category;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
@ -85,6 +86,30 @@ class CategoryController extends AdminController
$form->agent_id = Admin::user()->id;
$form->sort = $form->sort ?? 255;
})->deleting(function (Form $form) {
//获取到要删除分类的ID
$category_id = (int)$form->getKey();
//获取要删除类目的所有下级ID
$agent_id = Admin::user()->id;
$category = Category::where('agent_id', $agent_id)->pluck('pid', 'id')->toArray();
$ids = getChildCate($category_id, $category);
if (AgentProduct::query()->where('agent_id', $agent_id)->whereIn('category_id', $ids)->exists()) {
return $form->response()->error('该分类下已经发布产品,不允许删除');
}
});
}
}
//获取$pid下的所有子类目
function getChildCate($pid, $category): array
{
$cate_arr = [$pid];
foreach ($category as $k => $v) {
if ($v == $pid) {
$cate_arr = array_merge($cate_arr, getChildCate($k, $category));
}
}
return $cate_arr;
}
Loading…
Cancel
Save