yii2: Update values in two tables using single con

2019-09-10 08:31发布

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条回答
ゆ 、 Hurt°
2楼-- · 2019-09-10 09:33

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,]);
    }
}
查看更多
登录 后发表回答