【发布时间】:2014-08-31 01:49:17
【问题描述】:
我正在尝试将数据保存到 Yii 中具有两个不同模型的两个数据库表中。我已经查阅了 wiki:http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/ 和 http://www.yiiframework.com/forum/index.php/topic/52109-save-data-with-two-models/,但我仍然无法将数据保存到两个表中。我有两张桌子sales_rep_min_margin 和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,
));
}
我只需要将数据保存到表中,但视图中不需要“历史”表的数据。非常感谢任何帮助!有人向我提供了以下代码,但是,它不起作用:
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()) {
if (isset($_POST['SalesRepMinMarginHistory'])) {
$model2->attributes = $_POST['SalesRepMinMarginHistory'];
$model2->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model, 'model2' => $model2,
));
}
【问题讨论】: