views:

441

answers:

1

I've looked at other people's questions on this topic but can't seem to find where my error is coming from. Any help would be greatly appreciated. I'm including as much as I can think of that might help find the problem:

CREATE TABLE stocks (
id INT AUTO_INCREMENT NOT NULL,
user_id INT(11) UNSIGNED NOT NULL,
ticker VARCHAR(20) NOT NULL,
name VARCHAR(20),
rating INT(11),
position ENUM("strong buy", "buy", "sell", "strong sell", "neutral"),
next_look DATE,
privacy ENUM("public", "private"),
PRIMARY KEY(id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
 ENGINE=InnoDB DEFAULT CHARSET=utf8;



CREATE TABLE IF NOT EXISTS `stocks_tags` (
  `stock_id` INT NOT NULL,
  `tag_id` INT NOT NULL,
  PRIMARY KEY  (`stock_id`,`tag_id`),
  KEY `fk_stock_tag` (`tag_id`),
  KEY `fk_tag_stock` (`stock_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `stocks_tags`
  ADD CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_tag_stock` FOREIGN KEY (`stock_id`) REFERENCES `stocks` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;



CREATE TABLE tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tags VARCHAR(30),
UNIQUE(tags)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;

And the error I'm getting:

Database_Exception [ 1452 ]: Cannot add or update a child row: a foreign key constraint 
fails (`ddmachine`.`stocks_tags`, CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES  
`tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) [ INSERT INTO `stocks_tags` (`stock_id`, 
`tag_id`) VALUES (19, 'cash') ]

I did see that someone else had a similar problem based on their enum columns but don't think that's it.

+1  A: 

It means that the tag_id cash is missing from the tag table... shouldn't tag_id be an integer?

(in this query I mean)

INSERT INTO `stocks_tags` (`stock_id`, `tag_id`) VALUES (19, 'cash')
SeanJA
Yes, I must have been staring at the computer too long today! How ridiculous. I think this was complicated by the fact that I am using an ORM and so my models for it must be incorrect.
dscher