CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation

Hi,

I’m now in chapter 6 and have following problem.




http://localhost/trackstar2/index.php?r=issue/create&pid=4



If I want to create a new Issue to an existing Project I got following error.

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation

Here is the SQL Code that I’m using




-- Disable foreign keys

SET FOREIGN_KEY_CHECKS = 0 ;


-- Create tables section -------------------------------------------------


-- Table tbl_project


CREATE TABLE IF NOT EXISTS `tbl_project` (

  `id` INTEGER NOT NULL auto_increment,

  `name` varchar(128) NOT NULL,

  `description` text NOT NULL,

  `create_time` DATETIME default NULL,

  `create_user_id` INTEGER default NULL,

  `update_time` DATETIME default NULL,

  `update_user_id` INTEGER default NULL,

  PRIMARY KEY  (`id`)

) ENGINE = InnoDB

;


-- DROP TABLE IF EXISTS `tbl_issue` ;


CREATE TABLE IF NOT EXISTS `tbl_issue` 

( 

  `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,

  `name` varchar(256) NOT NULL,

  `description` varchar(2000), 

  `project_id` INTEGER,

  `type_id` INTEGER,

  `status_id` INTEGER,

  `owner_id` INTEGER,

  `requester_id` INTEGER,

  `create_time` DATETIME,

  `create_user_id` INTEGER,

  `update_time` DATETIME,

  `update_user_id` INTEGER  

) ENGINE = InnoDB

; 


-- DROP TABLE IF EXISTS `tbl_user` ;


-- Table User


CREATE TABLE IF NOT EXISTS `tbl_user` 

(

  `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,

  `email` Varchar(256) NOT NULL,

  `username` Varchar(256),

  `password` Varchar(256),

  `last_login_time` Datetime,

  `create_time` DATETIME,

  `create_user_id` INTEGER,

  `update_time` DATETIME,

  `update_user_id` INTEGER

) ENGINE = InnoDB

; 


-- DROP TABLE IF EXISTS `tbl_project_user_assignment` ;


-- Table User


CREATE TABLE IF NOT EXISTS `tbl_project_user_assignment`

(

  `project_id` Int(11) NOT NULL,

  `user_id` Int(11) NOT NULL,

  `create_time` DATETIME,

  `create_user_id` INTEGER,

  `update_time` DATETIME,

  `update_user_id` INTEGER,

 PRIMARY KEY (`project_id`,`user_id`)

) ENGINE = InnoDB

;




-- The Relationships 

ALTER TABLE `tbl_issue` ADD CONSTRAINT `FK_issue_project` FOREIGN KEY (`project_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;


ALTER TABLE `tbl_issue` ADD CONSTRAINT `FK_issue_owner` FOREIGN KEY (`owner_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT; 


ALTER TABLE `tbl_issue` ADD CONSTRAINT `FK_issue_requester` FOREIGN KEY (`requester_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT; 


ALTER TABLE `tbl_project_user_assignment` ADD CONSTRAINT `FK_project_user` FOREIGN KEY (`project_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;


ALTER TABLE `tbl_project_user_assignment` ADD CONSTRAINT `FK_user_project` FOREIGN KEY (`user_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;   


-- Insert some seed data so we can just begin using the database

INSERT INTO `tbl_user` 

  (`email`, `username`, `password`) 

VALUES 

  ('test1@notanaddress.com','Test_User_One', MD5('test1')),

  ('test2@notanaddress.com','Test_User_Two', MD5('test2'))    

;


-- Enable foreign keys

SET FOREIGN_KEY_CHECKS = 1 ;

who can help me?=

thx

The constraint violation could be due to:

  1. The project_id attempting to be inserted is not associated with a valid tbl_project.id value in the tbl_project table.

  2. The owner_id attempting to be inserted is not associated with a valid tbl_user.id value in the tbl_user table.

  3. The requester_id attempting to be inserted is not associated with a valid tbl_user.id value in the tbl_user table.

Have you inspected exactly what is attempting to be inserted and ensured all of these are valid values (i.e. they all are associated with valid data rows in their respective "parent" tables)?

If your application is running in debug mode (i.e.


defined('YII_DEBUG') or define('YII_DEBUG',true);

is in index.php entry script), you can view the actual sql statement attempting to be executing in the application log file (by default this is in protected/runtime/application.log).

The failure also occurs if you are using the code from the autors page!

/protected/runtime/application.log says




2010/09/27 15:54:40 [error] [system.db.CDbCommand] Error in executing SQL: INSERT INTO `tbl_issue` (`project_id`, `name`, `description`, `type_id`, `status_id`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)

in /var/www/trackstar/protected/controllers/IssueController.php (77)

in /var/www/trackstar/protected/controllers/IssueController.php (213)

in /var/www/trackstar/index.php (12)

2010/09/27 15:54:40 [error] [exception.CDbException] exception 'CDbException' with message '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 (`trackstar`.`tbl_issue`, CONSTRAINT `FK_issue_project` FOREIGN KEY (`project_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE)' in /var/www/yii/framework/db/CDbCommand.php:227

Stack trace:

#0 /var/www/yii/framework/db/ar/CActiveRecord.php(954): CDbCommand->execute()

#1 /var/www/yii/framework/db/ar/CActiveRecord.php(713): CActiveRecord->insert(NULL)

#2 /var/www/trackstar/protected/controllers/IssueController.php(77): CActiveRecord->save()

#3 /var/www/yii/framework/web/actions/CInlineAction.php(32): IssueController->actionCreate()

#4 /var/www/yii/framework/web/CController.php(300): CInlineAction->run()

#5 /var/www/yii/framework/web/filters/CFilterChain.php(129): CController->runAction(Object(CInlineAction))

#6 /var/www/trackstar/protected/controllers/IssueController.php(213): CFilterChain->run()

#7 /var/www/yii/framework/web/filters/CInlineFilter.php(59): IssueController->filterProjectContext(Object(CFilterChain))

#8 /var/www/yii/framework/web/filters/CFilterChain.php(126): CInlineFilter->filter(Object(CFilterChain))

#9 /var/www/yii/framework/web/filters/CFilter.php(41): CFilterChain->run()

#10 /var/www/yii/framework/web/CController.php(999): CFilter->filter(Object(CFilterChain))

#11 /var/www/yii/framework/web/filters/CInlineFilter.php(59): CController->filterAccessControl(Object(CFilterChain))

#12 /var/www/yii/framework/web/filters/CFilterChain.php(126): CInlineFilter->filter(Object(CFilterChain))

#13 /var/www/yii/framework/web/CController.php(283): CFilterChain->run()

#14 /var/www/yii/framework/web/CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)

#15 /var/www/yii/framework/web/CWebApplication.php(320): CController->run('create')

#16 /var/www/yii/framework/web/CWebApplication.php(120): CWebApplication->runController('issue/create')

#17 /var/www/yii/framework/base/CApplication.php(135): CWebApplication->processRequest()

#18 /var/www/trackstar/index.php(12): CApplication->run()

#19 {main} REQUEST_URI=/trackstar/index.php?r=issue/create&pid=3



Well, the book only covers adding an issue to project id #1. And because this issue CRUD is covered prior to User management (i.e. chapters 7 and 8 ), the assignment between a user and a project had to be explicitly executed (i.e. the SQL INSERT statement at the top of page 120). This only created an association between User #1 and User #2 with Project #1.

From your post, it looks as if you are attempting to update Project #4 (from your first post) and then in your application log, it looks as if you are attempting to add a new issue to project #3. So, it seems to me that you are not using the exact code/db content from the book.

I have re-tested chapter 6 code, and I am able to add issues to project #1 (again with the explicit assignment of User #1 and User #2 to project #1) without any errors.

Maybe providing a snapshot of the content in your database could help shed some light on the problem you are having.

thx for the answer

here is my mysql-dump


-- Disable foreign keys

SET FOREIGN_KEY_CHECKS = 0 ;


-- Create tables section -------------------------------------------------


-- Table tbl_project


CREATE TABLE IF NOT EXISTS `tbl_project` (

  `id` INTEGER NOT NULL auto_increment,

  `name` varchar(128) NOT NULL,

  `description` text NOT NULL,

  `create_time` DATETIME default NULL,

  `create_user_id` INTEGER default NULL,

  `update_time` DATETIME default NULL,

  `update_user_id` INTEGER default NULL,

  PRIMARY KEY  (`id`)

) ENGINE = InnoDB

;


-- DROP TABLE IF EXISTS `tbl_issue` ;


CREATE TABLE IF NOT EXISTS `tbl_issue` 

( 

  `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,

  `name` varchar(256) NOT NULL,

  `description` varchar(2000), 

  `project_id` INTEGER,

  `type_id` INTEGER,

  `status_id` INTEGER,

  `owner_id` INTEGER,

  `requester_id` INTEGER,

  `create_time` DATETIME,

  `create_user_id` INTEGER,

  `update_time` DATETIME,

  `update_user_id` INTEGER  

) ENGINE = InnoDB

; 


-- DROP TABLE IF EXISTS `tbl_user` ;


-- Table User


CREATE TABLE IF NOT EXISTS `tbl_user` 

(

  `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,

  `email` Varchar(256) NOT NULL,

  `username` Varchar(256),

  `password` Varchar(256),

  `last_login_time` Datetime,

  `create_time` DATETIME,

  `create_user_id` INTEGER,

  `update_time` DATETIME,

  `update_user_id` INTEGER

) ENGINE = InnoDB

; 


-- DROP TABLE IF EXISTS `tbl_project_user_assignment` ;


-- Table User


CREATE TABLE IF NOT EXISTS `tbl_project_user_assignment`

(

  `project_id` Int(11) NOT NULL,

  `user_id` Int(11) NOT NULL,

  `create_time` DATETIME,

  `create_user_id` INTEGER,

  `update_time` DATETIME,

  `update_user_id` INTEGER,

 PRIMARY KEY (`project_id`,`user_id`)

) ENGINE = InnoDB

;




-- The Relationships 

ALTER TABLE `tbl_issue` ADD CONSTRAINT `FK_issue_project` FOREIGN KEY (`project_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;


ALTER TABLE `tbl_issue` ADD CONSTRAINT `FK_issue_owner` FOREIGN KEY (`owner_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT; 


ALTER TABLE `tbl_issue` ADD CONSTRAINT `FK_issue_requester` FOREIGN KEY (`requester_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT; 


ALTER TABLE `tbl_project_user_assignment` ADD CONSTRAINT `FK_project_user` FOREIGN KEY (`project_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;


ALTER TABLE `tbl_project_user_assignment` ADD CONSTRAINT `FK_user_project` FOREIGN KEY (`user_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT;   


-- Insert some seed data so we can just begin using the database

INSERT INTO `tbl_user` 

  (`email`, `username`, `password`) 

VALUES 

  ('test1@notanaddress.com','Test_User_One', MD5('test1')),

  ('test2@notanaddress.com','Test_User_Two', MD5('test2'))    

;


-- Enable foreign keys

SET FOREIGN_KEY_CHECKS = 1 ;

Sorry, I did not mean the schema definition, but a look at what data is in the tables, specifically for the tables tbl_project and tbl_user.

Try this:

I don’t know why but it works for me.

I’m actually at the same point in that book and I’m receiving the same error message regarding the foreign key restraint failing.

Just out of curiosity, did you ever diagnose what was wrong?

Not sure if this helps… But just went through the same issue related to a Foreign Key constraint. After much trial & error, I realized ‘project_id’ was not in my ‘required’ rule in the rules() function in the issue model.

models/Issue.php:




public function rules()

{

    // NOTE: you should only define rules for those attributes that

    // will receive user inputs.

    return array(

        array('name, project_id', 'required'),

        .....

        ........

    );

}



Once I put ‘project_id’ in there, it saved fine.

Yes, you are right!

I also encountered the same error. 1st, i check the foreign keys, they were fine. Then i check the data of both tables, looks good as well. In the end, realized that for user input fields, i need to add in the rules.

Thanks for the tip!

I also had to put my foreign key (country) into the rules for integer only:


array('country', 'numerical', 'integerOnly'=>true, 'message'=>'Only numbers!')

Took me hours to find this! Why does Yii want to have it in this rule?!? Without putting it into the rule Yii ignores this attribute completely in the SQL statement.

Only attributes that appear in the rule-list are ‘safe’. Only safe attributes can be massively assigned.