Answer the question
In order to leave comments, you need to log in
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']);
}
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question