V
V
Victor Umansky2018-10-15 02:55:59
Yii
Victor Umansky, 2018-10-15 02:55:59

How to correctly delete one multilevel branch?

Hello!
The essence of the task is as follows, there is a yii2 gridview, a multi-level category of any nesting depth is displayed there, and it is necessary to make it so that when the user deletes the parent, the children should leave behind him, and behind them more children, and so on ad infinitum, depending on what nesting.
Here the recursion prompts me to think, if so, how to compose it correctly?
db category:
id | parent_id | status | title | ....
In the controller CategoryController. I only did the removal of the second nesting, but I can’t master the third nesting.
The picture shows three nestings, there can be 5 or 10 of them, how to implement mass deletion correctly!

public function actionDelete($id)
    {
       $child = Category::find()->where(['parent_id' => $id])->one();
        if ($child->parent_id != null) {
            $child->delete();
        }

        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

a5e49ffc70.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey, 2018-10-15
@VladimirAndreev

The best way is to add a foreign key from the swarm id to the parent_id field and the cascade property to on delete.
Well, or in a loop, without recursion, you have an id, you get all the ids who have parent_id, you search for them in the same way. When the set is empty, you stop the loop.

D
Dmitry Kim, 2018-10-15
@kimono

Try using nested sets or materialized path for this table.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question