Yuki_Kurokawa
Yuki_Kurokawa

Reputation: 31

Yii2 Update Parent Child

I have a structure table like this

enter image description here

I want to change record data field goid = 1, but I as you can see my code bellow, there's limit looping. Is there a better way to do it?

public function actionShareGoid($folder)
{
    $one = DokumenFolder::findOne($folder);
    $one->goid = '1';
    $one->update(false);

    $models_1 = DokumenFolder::find()->where(['parent_id'=>$one->id])->all();
    foreach ($models_1 as $key_1 => $model_1) {
        $model_1->goid = '1';
        $model_1->update(false);
        $models_2 = DokumenFolder::find()->where(['parent_id'=>$model_1->id])->all();
        foreach ($models_2 as $key_2 => $model_2) {
            $model_2->goid = '1';
            $model_2->update(false);
            $models_3 = DokumenFolder::find()->where(['parent_id'=>$model_2->id])->all();
            foreach ($models_3 as $key_3 => $model_3) {
                $model_3->goid = '1';
                $model_3->update(false);
                $models_4 = DokumenFolder::find()->where(['parent_id'=>$model_3->id])->all();
                foreach ($models_4 as $key_4 => $model_4) {
                    $model_4->goid = '1';
                    $model_4->update(false);
                }
            }
        }
    }

    return $this->redirect(Yii::$app->request->referrer);
}

Upvotes: 2

Views: 313

Answers (1)

Yuki_Kurokawa
Yuki_Kurokawa

Reputation: 31

Thanks to someone, I got the answer. ^_^

So here it is...

public function folderParent($id)
{
    $models = DokumenFolder::find()->where(['parent_id'=>$id])->all();
    foreach ($models as $key => $model) {
        $model->goid = '1';
        $model->update(false);
    }
}

public function actionShareGoid($id)
{
    $models = DokumenFolder::find()->where(['parent_id'=>$id])->all();
    foreach ($models as $key => $model) {
        $this->folderParent($model->id);
    }
    return $this->redirect(Yii::$app->request->referrer);
}

Upvotes: 1

Related Questions