清理后台分类数据

This commit is contained in:
Edward Yang 2022-11-09 17:53:57 +08:00
parent aa76941cf7
commit 97f3db810a
3 changed files with 46 additions and 4 deletions

View File

@ -15,10 +15,7 @@ class CategoryController extends Controller
public function index()
{
$categories = Category::with('description', 'children.description', 'children.children.description')
->where('parent_id', 0)
->get();
$categories = CategoryRepo::getAdminList();
$data = [
'categories' => CategoryResource::collection($categories),
];

View File

@ -2,6 +2,7 @@
namespace Beike\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@ -20,6 +21,11 @@ class Category extends Base
'active' => 'boolean',
];
public function parent(): BelongsTo
{
return $this->belongsTo(Category::class, 'parent_id');
}
public function children(): HasMany
{
return $this->hasMany(Category::class, 'parent_id');

View File

@ -22,6 +22,41 @@ class CategoryRepo
private static $allCategoryWithName = null;
/**
* 后台获取分类列表
* @return Builder[]|Collection
*/
public static function getAdminList()
{
self::cleanCategories();
return Category::with(['description', 'children.description', 'children.children.description'])
->where('parent_id', 0)
->get();
}
/**
* 清理分类数据
*/
public static function cleanCategories()
{
$categories = Category::with([
'parent',
'description',
])->get();
foreach ($categories as $category) {
if ($category->parent_id && empty($category->parent)) {
$category->parent_id = 0;
$category->save();
}
if (empty($category->description)) {
$category->delete();
}
}
}
public static function flatten(string $locale, $separator = ' > '): array
{
$sql = "SELECT cp.category_id AS id, TRIM(LOWER(GROUP_CONCAT(cd1.name ORDER BY cp.level SEPARATOR '{$separator}'))) AS name, c1.parent_id, c1.position";
@ -108,6 +143,10 @@ class CategoryRepo
if ($pathName) {
$pathName .= ' > ';
}
if (empty($path->pathCategory)) {
$path->delete();
continue;
}
$pathName .= $path->pathCategory->description->name;
}
$results[] = [