mysql外键(完整性约束违规)

时间:2016-01-19 06:40:30

标签: php mysql foreign-keys laravel-5.1

我正在开发一个小支持(票证)系统。我的表是票证和ticket_replies。

门票表的设计是

id|user_id|title|...

ticket_replies的设计如下:

id|ticket_id|...

现在我想从ticket表创建一个外键到ticket_replies表。此外键应保护ticket_replies表不被编辑,而不编辑之前的票证表。例如,如果故障单的ID更改,则应在“ticket_replies”中更改ticket_id。如果在故障单中删除故障单,则应在“ticket_replies”中将其删除。

我添加的外键如下所示:

ALTER TABLE `tickets` ADD FOREIGN KEY (`id`) REFERENCES `sampleauth`.`ticket_replies`(`ticket_id`) ON DELETE CASCADE ON UPDATE CASCADE;

创建此外键是成功的,但是当我尝试插入如下数据时:

            $ticket = new Ticket;
            $ticket->user_id = $user->id;
            $ticket->title = $request->title;
            $ticket->status = 0;
            $ticket->department_id = $request->departments;
            $ticket->save();

            //create new ticket_replie
            $ticket_replie = new Ticket_replie;
            $ticket_replie->ticket_id = $ticket->id;
            $ticket_replie->user_id = $user->id;
            $ticket_replie->text = $request->question;
            $ticket_replie->save();

它没说:

  

完整性约束违规:1452无法添加或更新子行:   外键约束失败(sampleauth.tickets,CONSTRAINT   tickets_ibfk_1 FOREIGN KEY(id)REFERENCES ticket_replies(ticket_id)   ON DELETE CASCADE ON UPDATE CASCADE)(SQL:插入票证   (user_id,title,status,department_id,updated_at,created_at)值   (1,sasa,0,1,2016-01-18 23:03:21,2016-01-18 23:03:21))

我理解为什么会发生这种情况(因为当我创建新票证时,Mysql会检查来自ticket_replies的ticket_id是否与ticket_id匹配),但我不知道如何解决这个问题,任何想法?

2 个答案:

答案 0 :(得分:1)

您需要将票据从 ticket_replies 引用到票证

这是常见规则:

如果您将列命名为 {table_name} _id (ticket_replies.ticket_id),则需要将其引用到 {table_name} .id (ticket.id)。< / p>

因此,您需要删除现有的外键并创建新的:

ALTER TABLE tickets DROP FOREIGN KEY (id);

ALTER TABLE ticket_replies ADD FOREIGN KEY (ticket_id) REFERENCES ticket(id) ON DELETE CASCADE ON UPDATE CASCADE;

答案 1 :(得分:1)

那些会起作用

ALTER TABLE `tickets` DROP FOREIGN KEY `ticket_ibfk_1`;
ALTER TABLE ticket_replies ADD FOREIGN KEY (ticket_id) REFERENCES ticket(id) ON DELETE CASCADE ON UPDATE CASCADE;

这些是我运行的完整测试代码。

CREATE TABLE `tickets` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `ticket_replies` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ticket_id` int(10) unsigned NOT NULL,
  `reply` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

ALTER TABLE ticket_replies ADD FOREIGN KEY (ticket_id) REFERENCES tickets(id) ON DELETE CASCADE ON UPDATE CASCADE;

insert into tickets(name) values('123');
insert into ticket_replies(ticket_id, reply) values(LAST_INSERT_ID(),'123');