错误:
Cannot delete or update a parent row: a foreign key constraint fails
(`databasename`.`webapp_requestsuser`, CONSTRAINT `fk_perRequests` FOREIGN KEY
(`requestsid`) REFERENCES `webapp_requests` (`id`))
创建查询:
CREATE TABLE `webapp_requests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`opentime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`starttime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`description` longtext,
`duration` double DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
CREATE TABLE `webapp_requestsuser` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` int(11) NOT NULL,
`status` tinyint(4) DEFAULT '0',
`requestsid` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `requestsid` (`requestsid`),
CONSTRAINT `fk_perRequests` FOREIGN KEY (`requestsid`) REFERENCES `webapp_requests` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
内容webapp_requests:
_______________________________________
| id = 2 |
| userid = 2 |
| opentime = 2015-11-24 16:26:44 |
| starttime = 2015-11-24 16:26:44 |
| description = This is a description |
| duration = 5.0 |
_______________________________________
内容webapp_requestsuser:
_______________________________________
| id = 3 |
| user = 1 |
| status = 0 |
| requestsid = 2 |
_______________________________________
删除查询:
DELETE FROM `webapp_requests` WHERE `id` = 2;
这是我想要在webapp_requests中删除行时所得到的。
我认真地尝试了这里已经提出的所有可能的问题但无法解决。是的,我知道FK是如何运作的。此外,我使用此函数来插入数据:
public function createRequest($userid, $recipients, $description, $duration, $starttime)
{
$existcheck = $this->db->query('SELECT * FROM `webapp_requests` WHERE `userid`=('.$this->db->escape($userid).')');
// Check if already a request is registered
if ($existcheck->num_rows() > 0) {
return false;
}
// First add the request
$query = $this->db->query('INSERT INTO `webapp_requests`( `userid`, `description`, `duration`, `starttime`) VALUES (' . $this->db->escape($userid) . ',' . $this->db->escape($description) . ',' . $this->db->escape($duration) . ',' . $this->db->escape($starttime) . ')');
$id = $this->db->insert_id();
if (!$query) {
return false;
} else {
// Then add the users to the request
$tokens = [];
foreach($recipients as $recipient) {
$this->db->query('INSERT INTO `webapp_requestsuser`(`user`,`requestsid`) VALUES (' . $this->db->escape($recipient) . ',' . $this->db->escape($id) . ')');
$pushValue = $this->db->query('SELECT * FROM `notificationtoken` WHERE `user`=('.$this->db->escape($recipient).')')->row();
array_push($tokens, $pushValue);
}
return $tokens;
}
}
答案 0 :(得分:2)
你的“创造”工作正常。
问题是您要删除引用的表(webapp_requests
)中违反约束的行。
因此它会在引用表(webapp_requestsuser
)中孤立一行。那里至少会有一行说我的父母现在在哪里?我的requestsid
是2,但引用的表中没有id = 2。
所以dbengine说,你告诉我不要允许它,我不允许它。
对于那些想要查看级联删除示例的人,请参阅answer of mine here。