How to remove one multilevel branch?

Hello!

The essence of the problem is, there yii2 gridview, to display multi-level categories to any depth of nesting should be done so that when the user removes the parent for him to leave the children, and behind them are still children and so on to infinity, despite what the nesting.
Here is the idea I have suggests recursion, if Yes, how it to make?

dB category:
id | parent_id | status | title | ....

In the controller CategoryController. I did remove the second nesting, but the third nesting is not able to overpower.
The picture shows three nesting them may be 5 or 10 on how to properly implement a mass delete!
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
March 12th 20 at 10:45
2 answers
March 12th 20 at 10:47
The best way is to add a foreign key with Roy on the field id parent_id and property in cascade on delete.
Well, or in a loop, without recursion, you have id get all id, parent_id from whom he, looking on them the same way. When the set is empty - stop the cycle.
But I can show this implementation? - carolina_Kiehn commented on March 12th 20 at 10:50
@carolina_Kiehnthat from? - eusebio.Maye commented on March 12th 20 at 10:53
@eusebio.Maye, I was referring to a loop without recursion, I want to see the implementation itself, I just thought that there will only recursion? - carolina_Kiehn commented on March 12th 20 at 10:56
@carolina_Kiehn,

$delete_ids = [$delete_id];
while(true) {

$next_ids = get(!isset($next_ids ? $delete_ids:$next_ids));
if(0===\count($next_ids)) break;
$delete_ids = \array_merge($delete_ids, $next_ids);
}
- eusebio.Maye commented on March 12th 20 at 10:59
March 12th 20 at 10:49
Try using nested sets or materialized path for this table.
Why would I want a ready solution, I want to understand how it is done, so interesting!! - carolina_Kiehn commented on March 12th 20 at 10:52
@carolina_Kiehn, this is not a finished solution, it is the practice to work with nested trees. - Stone_Kri commented on March 12th 20 at 10:55
@Stone_Kri, That is, there was no sight to install the extension itself.... I thought that in the extension there everything is already implemented, and to delovati yourself!) - carolina_Kiehn commented on March 12th 20 at 10:58
@carolina_Kiehn, no, Victor, I do not suggest you to install the extensions, I only propose to read how this is implemented in the theory.
For example, about nested sets here or hereor here - Stone_Kri commented on March 12th 20 at 11:01

Find more questions by tags Yii