嵌套集保存到数据库

时间:2017-10-12 19:54:28

标签: ajax laravel nested-sets jqtree

我正在尝试使用Laravel应用程序实现jqTree。

  1. Controller获取数据并返回视图:

    public function index()
    {
        $categories = Category::get(['id', 'name', '_lft', '_rgt', 'parent_id'])->toTree();
        return view('category.index', [
            'categories' => $categories
        ]);
    }
    
  2. 这是一个视图(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 },
    });
    
    }
  3. 这样可以正确构建树,我可以拖动&丢弃物品。但是,我想将重新排序的树保存回数据库。这是控制器中的post方法:

    Type error: Argument 1 passed to Kalnoy\\Nestedset\\QueryBuilder::rebuildTree() must be of the type array, string given
    
  4. 调用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

    嵌套集合为lazychaser/laravel-nestedset

1 个答案:

答案 0 :(得分:1)

json您需要$request->data;使用json_decode()将其解析为数组,并将第二个参数解析为true

see the manual

  

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);