我正在尝试使用Laravel应用程序实现jqTree。
Controller获取数据并返回视图:
public function index() { $categories = Category::get(['id', 'name', '_lft', '_rgt', 'parent_id'])->toTree(); return view('category.index', [ 'categories' => $categories ]); }
这是一个视图(javascript部分):
var data = {!! $categories !!}; $('#tree').tree({ data: data, dragAndDrop: true, onDragStop: handleMove, }); function handleMove() { var treeData = $('#tree').tree('toJson');}$.ajax({ url: 'category', type: 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: { data: treeData }, });
这样可以正确构建树,我可以拖动&丢弃物品。但是,我想将重新排序的树保存回数据库。这是控制器中的post方法:
Type error: Argument 1 passed to Kalnoy\\Nestedset\\QueryBuilder::rebuildTree() must be of the type array, string given
调用rebuildTree方法后,我收到此错误:
public function store(Request $request) { $data = $request->data; $result = Category::rebuildTree($data); ... }
我试过这个:
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
答案 0 :(得分:1)
json
您需要$request->data;
使用json_decode()
将其解析为数组,并将第二个参数解析为true
ASSOC
如果为TRUE,则返回的对象将转换为关联对象 阵列。
public function store(Request $request)
{
$result = Category::rebuildTree(json_decode($request->data,True));
...
}
如果你需要在$data
中传递它,那么就这样传递它。
$data = json_decode($request->data,True);
<强>替代地强>
foreach ($request->data as $value)
$array[] = $value->name;
然后将此$array
传递到您的查询中,就像这样
$result = Category::rebuildTree($array);