M
M
Maxim Volkov2020-12-24 16:53:52
Laravel
Maxim Volkov, 2020-12-24 16:53:52

Laravel Nestedset - category tree, problem with updating data. How to fix?

The category tree is built using the Kalnoy\Nestedset\NodeTrait package . When the package and migrations are installed, a number of fields are created in the database table: parent_id , _lft and _rgt .

Everything works, but there were difficulties, or some kind of misunderstanding associated with updating the categories.
When creating a new category, it is enough to assign parent_id - the id data of the parent category , and the category is created with the required nesting level.

However, when updating the data, I get an error message,
5fe49c545331e222656000.jpeg

According to this error message, Nestedset cannot move a node into itself. But in this case, I'm just trying to save the updated data.
Resource controller UPDATE method:

public function update(Request $request, $id)
    {
        $category = Category::find($id);
        $data = $request->all();
         //$data - внесение изменений в данные для последующего сохранения
        $category->update($data);
        return redirect()->route('categories.index')->with('success', 'Категория изменена');
    }


I did not find a solution to the problem in the documentation. Please help the community to resolve this issue. Who has experience and worked with Kalnoy\Nestedset\NodeTrait, where to look, what to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Volkov, 2020-12-25
@voland700

The problem is solved, I will describe the solution.
1. In my case, there was an error in the logic. I tried to save the ID of the category being edited as parent_id, as a result I received the Kalnoy\Nestedset\NodeTrait message stating that the category cannot be nested into itself. An error occurred while copying the category creation form into a data editing template.
2. Simply assigning parent_id - parent category id data, is not enough to build Kalnoy\Nestedset\NodeTrait tree of nested categories. To recalculate the tree, if a parent_id is directly assigned to a new category, it is necessary to run the method:
$category::fixTree();
this method starts the recalculation of the tree based on the parent_id data , fills in the field values ​​in the table_lft and _rgt , on the basis of which the nesting tree is built.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question