I’m attempting to save data to two db tables with two different models in Yii. I’ve consulted the wiki: http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/ and http://www.yiiframework.com/forum/index.php/topic/52109-save-data-with-two-models/, yet I still can’t get the data to save to both tables. I have two tables sales_rep_min_margin and sales_rep_min_margin_history:
CREATE TABLE sales_rep_min_margin
(
id
int(11) NOT NULL AUTO_INCREMENT,
username
varchar(32) NOT NULL,
domestic
int(2) NOT NULL,
overseas
int(2) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE sales_rep_min_margin_history
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`min_margin_id` int(11) NOT NULL,
`from` int(11) DEFAULT NULL,
`to` int(11) DEFAULT NULL,
`update_username` varchar(32) NOT NULL,
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `min_margin_id` (`min_margin_id`),
CONSTRAINT `sales_rep_min_margin_history_ibfk_1` FOREIGN KEY (`min_margin_id`) REFERENCES `sales_rep_min_margin` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
My SalesRepMinMarginController code (right now) is:
public function actionCreate() {
$model = new SalesRepMinMargin;
$model2 = new SalesRepMinMarginHistory;
//Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation($model);
if (isset($_POST['SalesRepMinMargin'])) {
$model->attributes = $_POST['SalesRepMinMargin'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
if (isset($_POST['SalesRepMinMarginHistory'])) {
$model2->attributes = $_POST['SalesRepMinMarginHistory'];
$model2->save();
$this->render('create', array(
'model' => $model,
));
}
}
and ‘SalesRepMinMarginHistoryController’:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['SalesRepMinMarginHistory']))
{
$model->attributes=$_POST['SalesRepMinMarginHistory'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
I just need to save the data to the tables, but I don’t need the ‘history’ table’s data in the view. Any help is greatly apreciated!