我有產品視圖。我想添加到此視圖類別樹中。我想到了jsTree。我在我的項目中使用 Laravel 7 和 kalnoy/nestedset 和https://www.jstree.com小米遷移文件: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 格式?
1 回答

搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
好吧,我不知道你是否需要幫助來查看數據或數據格式,但我會盡力幫助解釋 json 的格式,基本元素必須是 3:- Id:當前的唯一標識符元素。- 父母:來自父母的ID,或在沒有父母時使用#。- 文本:顯示項目名稱。
您當前的輸出數據無法接受 jsTree 格式,您必須針對此格式進行調整:
$('#yourdata').jstree({ 'core' : {
'data' : [
{"id": 1,"parent":"#","text": "- Books"},
{"id": 2,"parent":"1","text": "-- Comic Book"}
]
}
});
它將顯示:
+ Book
-- Comic Book
作為子類別
我希望它有所幫助。
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報
0/150
提交
取消