简体   繁体   中英

Update two models with one view not working in Yii?

Can anybody help me resolve my issue? I'm able to do create new records but I can't modify or update my existing records.

Here is my source code:

public function actionCreate() {
    $model = new Branchmaster;
    $user = new Usermaster;
    if(isset($_POST['Branchmaster'], $_POST['Usermaster'])) {
      $model->attributes=$_POST['Branchmaster'];
      $user->attributes=$_POST['Usermaster'];
      $valid=$model->validate();
      $valid=$user->validate() && $valid;
      if($valid){
         $model->save();
         $chnuser->save();                   
         $this->redirect(array('view','id'=>$model->Id));
      }
    }
    $this->render('create',array(
      'model'=>$model,
      'user'=>$user,
    ));
  }

  public function actionUpdate($id) {
    $model=$this->loadModel($id);
    $user = Usermaster::model()->findByAttributes(array('branch_id'=>$model->Id));
    if(isset($_POST['Branchmaster'], $_POST['Usermaster'])) {
      $model->attributes=$_POST['Branchmaster'];
      $user->attributes=$_POST['Usermaster'];

      $valid=$model->validate();
      $valid=$user->validate() && $valid;
      if($valid){
        $model->save();
        $user->save();
        $this->redirect(array('view','id'=>$model->Id));
      }
    }
    $this->render('update',array(
      'model'=>$model,
      'user'=>$user,
    ));
  }

I need help for this problem... Thanks in advance!

Instead of find 'findByAttr' so that will be

// pls note tht $id must be a primary key of this particular model

$user = Usermaster::model()->findByPk($id);

// If the situation don't allow a primary key then we can go for query execution

$update = Yii::app()->db->createCommand()
->update('usermaster', array('field1'=>'value','field2'=>'value2'),
'branch_id=:id',array(':id'=>$branch_id));

You have to check if id is exited than u have to do update...

use findByPk to load model...

than do process to same is above here is sample code. you have to implement like these

         $model->attributes=$_POST['Branchmaster'];
         $user_post = $_POST['Usermaster'];
         $id = $user_post['id'];
         $user =  ModelName::model()->findByPk($id); 
         $user->variable_name = $variable_value


         $valid=$model->validate();
         $valid=$user->validate() && $valid;
         if($valid){
             $model->save();
             $user->save();
             $this->redirect(array('view','id'=>$model->Id));
         }

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM