yii2: Update values in two tables using single controller action?

天大地大妈咪最大 提交于 2019-12-12 06:37:19

问题


I have two tables table1 and table2 and I am trying to update row in these two table.I have same values on both table but id is different so i tried like this, my controller,

public function actionUpdate($id)
  {
   $model = $this->findModel($id);
   if ($model->load(Yii::$app->request->post()) && $model-     >validate()) {
         Employee::find()->where(['Id' => $id])->one()->update();
         User::find()->where(['User_id' =>$id])->one()->update();
         if ( $model->save()) { 
        return $this->redirect(['index']);
         }
    } else {
        return $this->render('update', [
            'model' => $model,]);
    }
}

I have table like this

CREATE TABLE Employee ( Id int(11) NOT NULL,Company_company_id int(100) NOT NULL,Company_name varchar(100) NOT NULL, Employee_id int(100) NOT NULL, Name varchar(100) NOT NULL,Email_id varchar(100) NOT NULL,Password varchar(16) NOT NULL,Joining_date date NOT NULL,Confirmation_date date NOT NULL, Relieving_date date NOT NULL,Leaves_Available int(25) NOTNULL,Statusenum('Active','Inactive') NOT NULL,)

CREATE TABLE User (Id int(15) NOT NULL, Name varchar(100) NOT NULL,Email_id varchar(100) NOT NULL,Password varchar(16) NOT NULL,Status enum('Active','Inactive') NOT NULL,)

I tried like this but i can't update both table
pls anyone help me Thanks in advance


回答1:


Try This :

public function actionUpdate($id)
  {

   if ($model->load(Yii::$app->request->post()) && $model->validate()) 
   {
        $modelEmp= Employee::find()->where(['Id' => $id])->one();
        $modelUser= User::find()->where(['User_id' =>$id])->one();

        $modelEmp->Name=$_POST['name']; // use your field names
        $modelEmp->Email_id=$_POST['email_id'];

        $modelUser->Name=$_POST['name'];
        $modelUser->Email_id=$_POST['email_id'];

         if ( $modelEmp->save() && $modelUser->save()) { 
            return $this->redirect(['index']);
         }
    }
    else {
        return $this->render('update', [
            'model' => $model,]);
    }
}


来源:https://stackoverflow.com/questions/37850891/yii2-update-values-in-two-tables-using-single-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!