Update Two Table By Using Loadmodel

public function actionUpdate($id)

{


	$model=$this->loadModel($id);





	// Uncomment the following line if AJAX validation is needed


	// $this->performAjaxValidation($model);





	if(isset($_POST['Employees']))


	{


	    $model2=new Staffrole;


		$model->attributes=$_POST['Employees'];


		$model2->attributes=$_POST['Staffrole'];


		$model2 = $model2::$model()->findByPk($id);





        $model2->attribute = 'update value?';





        $model2->save();


		if($model->save())


			$this->redirect(array('view','id'=>$model->empid));


	}





	$this->render('update',array(


		'model'=>$model,


	));


}

Hello alexOnDemand!

I recommend for you to use foreign keys, if you do so you can fetch data from model relations no need to write sql and so many advantages.

plus your code is erroneous;

for an existing record, according to your code you’re always creating a new object of $model2=new Staffrole;

if I understood you correctly you’re looking for this


$model2 = Staffrole::$model()->findByPk($staffRoleId);

Please can you explain the scenario bit,

I would approach it as following




public function actionUpdate($id)

{

	$model=$this->loadModel($id);

	$model2=Staffrole::model()->findByPk($id);


	// Uncomment the following line if AJAX validation is needed

	// $this->performAjaxValidation($model);


	if (isset($_POST['Employees']))

	{

		$model->attributes=$_POST['Employees'];

		$model2->attributes=$_POST['Staffrole'];

		$valid = $model->valid() && $model2->valid();

		if ($valid)

		{

			if ($model->save() && $model2->save())

				$this->redirect(array('view','id'=>$model->empid));

		}

	}


	$this->render('update',array(

		'model'=>$model,

	));

}

This wiki article is good and relevant. Recommended.