Yii2更新父子

时间:2016-10-25 07:07:28

标签: php yii2

我有一个像这样的结构表

enter image description here

我想更改记录数据字段goid = 1,但我可以看到我的代码如下,有限制循环。有没有更好的方法呢?

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);
}

1 个答案:

答案 0 :(得分:1)

感谢某人,我得到了答案。 ^ _ ^

所以这就是......

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);
}