我正在尝试使用 Laravel 应用程序实现 jqTree。
控制器获取数据并返回视图:
公共函数索引() { $categories = Category::get(['id', 'name', '_lft', '_rgt', 'parent_id'])->toTree(); 返回视图('category.index',[ '类别' => $类别 ]); }
这是一个视图(javascript部分):
变量数据 = {!!$类别!!}; $('#tree').tree({ 数据:数据, 拖放:真, onDragStop:句柄移动, }); 函数句柄移动(){ var treeData = $('#tree').tree('toJson');
}$.ajax({ url: 'category', type: 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: { data: treeData }, });
这可以正确构建树,我可以拖放项目。但是,我想将重新排序的树保存回数据库。这是控制器中的 post 方法:
公共功能存储(请求 $request) { $data = $request->数据; $result = Category::rebuildTree($data); ... }
调用rebuildTree 方法后,我收到此错误:
Type error: Argument 1 passed to Kalnoy\\Nestedset\\QueryBuilder::rebuildTree() must be of the type array, string given
我试过这个:
public function store(Request $request)
{
$data = $request->data;
$data = json_decode($request->data);
$array_data = (array) $data;
$result = Category::rebuildTree($data);
...
}
然而,这会返回:
不能将 stdClass 类型的对象用作数组
如何获取传递的数据数组以便我可以使用rebuildTree()
方法和更新数据库?
这是一个结果dd($request->data):
[{"name":"Storage","id":3,"_lft":17,"_rgt":18,"parent_id":null,"is_open":true,
"children":[{"name":"Laptops","id":1,"_lft":1,"_rgt":10,"parent_id":null,"is_open":true,
"children":[{"name":"Monitors","id":2,"_lft":11,"_rgt":16,"parent_id":null,
"children":[{"name":"IPS","id":5,"_lft":14,"_rgt":15,"parent_id":2}]},
{"name":"Macbook","id":6,"_lft":2,"_rgt":3,"parent_id":1},
{"name":"Acer","id":7,"_lft":4,"_rgt":5,"parent_id":1},
{"name":"New Subcategory Name","id":8,"_lft":6,"_rgt":7,"parent_id":1},
{"name":"New Subcategory ame","id":9,"_lft":8,"_rgt":9,"parent_id":1}]}]},
{"name":"Memory","id":4,"_lft":19,"_rgt":20,"parent_id":null}]
另外,要明确一点:我正在使用jqTree