添加新的記錄它給出了一個錯誤:Yii中增加新的記錄錯誤:1452無法添加或更新子行,外鍵約束失敗
1452 Cannot add or update a child row: a foreign key constraint fails
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 failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
money_investment
.data
, CONSTRAINTFK_data_users
FOREIGN KEY (id
) REFERENCESusers
(id
)). The SQL statement executed was: INSERT INTOdata
(investment_amount
,withdrawals
,investment_yield
,account_balance
,status_account
) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)