我有产品视图。我要添加到此视图类别树。我想到了jsTree。
我在我的项目Laravel 7中使用了kalnoy / nestedset和https://www.jstree.com
Mi迁移文件:
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('category_name', 155);
$table->string('description', 155)->nullable();
$table->string('keywords', 155)->nullable();
$table->longText('content')->nullable();
$table->char('enable', 1)->default(0);
$table->string('photo', 155)->nullable();
$table->bigInteger('order')->default(0);
$table->string('slug', 160)->nullable();
NestedSet::columns($table);
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
在控制器中,我有:
public function categoryTree(CategoryRepositoryInterface $categoryRepository, Request $request)
{
$nodes = $this->getCategoriesTree($categoryRepository->getTree());
return $nodes;
}
private function getCategoriesTree($nodes): array
{
$categoryArray = array();
$traverse = function ($categories, $prefix = '-') use (&$traverse, &$categoryArray) {
foreach ($categories as $category) {
$categoryArray[] = ['id' => $category->id, 'name' => $prefix . ' ' . $category->category_name];
$traverse($category->children, $prefix . '-');
}
};
$traverse($nodes);
return $categoryArray;
}
在存储库中:
public function getTree()
{
return $this->model->orderBy('order', 'ASC')->get()->toTree();
}
我的模型是类别。
结果我有:https://pastebin.com/uErKGgHP
如何将数据转换为jsTree格式?
答案 0 :(得分:1)
好吧,我不知道您是否需要帮助以查看数据或数据格式,但我会尽力帮助解释json的格式,essencial元素必须为3: -ID:当前元素的唯一标识符。 -父级:父级的ID,如果没有父级,则使用#。 -文字:显示商品名称。
您当前的输出数据无法以jsTree格式接受,您必须对此格式进行调整:
$('#yourdata').jstree({ 'core' : {
'data' : [
{"id": 1,"parent":"#","text": "- Books"},
{"id": 2,"parent":"1","text": "-- Comic Book"}
]
}
});
它将显示:
+ Book
-- Comic Book
作为子类别
希望对您有帮助。