如何在 Laravel-Admin 后台中实现分类按层级显示

admin 阅读:90 2024-02-20
在 Laravel-Admin 后台管理系统中,如果你需要展示分类数据,并按层级结构显示,可以通过以下步骤实现。本文将介绍如何利用 Laravel-Admin 的表单选择器以及递归方法来实现此功能。 先展示效果:

步骤一:数据库设计

首先,确保数据库中的分类表具有适当的结构。你需要为每个分类添加一个 parent_id 字段,用于表示其父分类。例如:

Schema::create('article_categories', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('parent_id')->nullable();
    $table->string('title');
    // 其他字段...
    $table->timestamps();
});

步骤二:定义模型关系

在分类模型中定义父子关系的方法,以便在树形结构中轻松获取分类及其子分类。

class ArticleCategory extends Model
{
    public function children()
    {
        return $this->hasMany(ArticleCategory::class, 'parent_id');
    }
}

步骤三:编写加载分类的方法

在后台控制器中编写一个方法,用于加载分类数据并返回给表单选择器。此处我们使用递归方法来构建分类树。

public function loadCategories(Request $request)
{
    $siteId = $request->get('q');

    $topCategories = ArticleCategory::where('site_id', $siteId)
        ->whereNull('parent_id')
        ->get(['id', 'title as text']);

    $categories = $this->buildCategoryTree($topCategories, $siteId);

    return $categories;
}

protected function buildCategoryTree($categories, $siteId, $parentId = null)
{
    $tree = [];

    foreach ($categories as $category) {
        $children = ArticleCategory::where('site_id', $siteId)
            ->where('parent_id', $category->id)
            ->get(['id', 'title as text']);

        $node = [
            'id' => $category->id,
            'parent_id' => $parentId,
            'text' => $category->text,
        ];

        if ($children->isNotEmpty()) {
            $node['children'] = $this->buildCategoryTree($children, $siteId, $category->id);
        }

        $tree[] = $node;
    }

    return $tree;
}

步骤四:在后台表单中使用选择器

在后台表单中使用 Laravel-Admin 提供的选择器,并指定加载分类数据的接口地址。

$form->select('site_id')->options(WebsiteConfigList::pluck('name', 'id'))->load('cid', '/admin/load-categories')->required();
$form->select('cid', __('admin.category'))->required();

通过以上步骤,你可以在 Laravel-Admin 后台中实现分类按层级显示的功能。这样的设计使得管理者可以更加方便地管理和浏览分类数据,提高了用户体验。
标签: Laravel-Admin
声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!