mIRU mIRU - 6 months ago 27
PHP Question

Yii on adding new record error : 1452 Cannot add or update a child row: a foreign key constraint fails

Adding new record it gives an error:


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'),
);
}


Here is my code for adding a new record:

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
)
);
}


Here is the first table:

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 ;


and the second table:

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 ;


and it gives this error:


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
, CONSTRAINT
FK_data_users
FOREIGN KEY (
id
) REFERENCES
users
(
id
)). The SQL statement executed was: INSERT INTO
data
(
investment_amount
,
withdrawals
,
investment_yield
,
account_balance
,
status_account
) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)

Answer

Thank you for help, I fixed my problem.

I added $data->id=$users->id; because second table had no idea about the id. See here.

if($valid){
$users->save();
$data->id=$users->id;
$data->save();


$this->redirect(
    array('view_record',
        'id'=> $users->id)
    );
}