添加新记录会出错:
1452 无法添加或更新子行:外键约束失败
public function relations()
{
return array(
'data' => array(self::HAS_ONE, 'Data', 'id'),
);
}
这是我添加新记录的代码:
public function actionAdd_Record()
{
$users = new Users();
$data = new Data();
if (isset($_POST['Users']) && isset($_POST['Data'])) {
if(!empty($_POST['Users_password'])) $_POST['Users']['password']=md5($_POST['Users_password']);
$users->created_date=date('Y-m-d H:i:s');
CActiveForm::validate(array($users, $data));
$users->attributes = $_POST['Users'];
$data->attributes = $_POST['Data'];
$valid=$users->validate();
$valid=$data->validate() && $valid;
if($valid){
$users->save();
$data->save();
$this->redirect(
array('view_record',
'id'=> $users->id)
);
}
}
$this->render(
'add_record', array(
'users'=> $users,
'data'=>$data
)
);
}
这是第一个表:
CREATE TABLE IF NOT EXISTS `data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`investment_amount` float DEFAULT '0' COMMENT '投資額',
`withdrawals` float DEFAULT '0' COMMENT '引出額',
`investment_yield` float DEFAULT '0' COMMENT '運用利回り',
`account_balance` float DEFAULT '0' COMMENT '口座残高',
`status_account` enum('open','closed') DEFAULT 'open',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
和第二张表:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(128) NOT NULL,
`password` varchar(128) NOT NULL,
`name` varchar(300) NOT NULL COMMENT '氏名',
`email` varchar(200) NOT NULL,
`user_type` enum('normal','admin') NOT NULL DEFAULT 'normal',
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
它给出了这个错误:
CDbCommand 未能执行 SQL 语句:SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
money_investment
.data
, CONSTRAINTFK_data_users
FOREIGN KEY (id
) REFERENCESusers
(id
))。执行的 SQL 语句为: INSERT INTOdata
(investment_amount
,withdrawals
,investment_yield
,account_balance
,status_account
) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)