Aliweb
Aliweb

Reputation: 1951

adding relation between mysql tables in Codeigniter

I'm using Codeigniter and want to add relation between the posts and comments tabels.

posts:

CREATE TABLE IF NOT EXISTS `posts` (
`post_id` int(5) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) COLLATE utf8_persian_ci NOT NULL,
`slug` varchar(100) COLLATE utf8_persian_ci NOT NULL,
`content` text COLLATE utf8_persian_ci NOT NULL,
`time` varchar(10) COLLATE utf8_persian_ci NOT NULL,
`num_of_comments` int(3) NOT NULL,
`cat` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`tags` varchar(100) COLLATE utf8_persian_ci NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=15 ;  

comments:

CREATE TABLE IF NOT EXISTS `comments` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`content` text COLLATE utf8_persian_ci NOT NULL,
`date` varchar(100) COLLATE utf8_persian_ci NOT NULL,
`time` varchar(100) COLLATE utf8_persian_ci NOT NULL,
`name` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`email` varchar(30) COLLATE utf8_persian_ci NOT NULL,
`image` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`ip` varchar(16) COLLATE utf8_persian_ci NOT NULL,
`submit` int(1) NOT NULL,
`reply` text COLLATE utf8_persian_ci NOT NULL,
`reply_date` varchar(100) COLLATE utf8_persian_ci NOT NULL,
`reply_time` varchar(100) COLLATE utf8_persian_ci NOT NULL,
`post_id` int(5) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `post_id` (`post_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=26 ;  

but it prints this error:

SQL query:

ALTER TABLE  `comments` ADD FOREIGN KEY (  `post_id` ) REFERENCES  `codeig`.`posts` (

`post_id`
) ON DELETE CASCADE ON UPDATE CASCADE ;

MySQL said: 

#1452 - Cannot add or update a child row: a foreign key constraint fails (`codeig`.     <result 2 when explaining filename '#sql-fc8_dd'>, CONSTRAINT `#sql-fc8_dd_ibfk_1` FOREIGN  KEY (`post_id`) REFERENCES `posts` (`post_id`) ON DELETE CASCADE ON UPDATE CASCADE)  

and i don't know what is talking about at all.
please help...

Upvotes: 0

Views: 1006

Answers (1)

ghostika
ghostika

Reputation: 1503

Where did you write this query? Or this was generated by codeigniter? Try this in any sql administration tool:

ALTER TABLE comments ADD FOREIGN KEY (post_id) REFERENCES posts(post_id) ON DELETE CASCADE ON UPDATE CASCADE ;

You don't need the codeig part, I'm assume that is the database name.

Upvotes: 3

Related Questions