我正在处理一个有外键错误的新脚本。
我有以下表格:request
,category
和request_category
。
表category
中现在有6个类别,所以这一切都很好。
我的脚本将数据插入到request
表中,之后它会尝试向request_category
添加一个条目,但这就是失败的地方。
代码:
$oUser = new User();
$oUser->firstname = $this->oLibrary->Request->post('firstname');
$oUser->initials = $this->oLibrary->Request->post('initials');
$oUser->lastname = $this->oLibrary->Request->post('lastname');
$oUser->zip = $this->oLibrary->Request->post('zip');
$oUser->city = $this->oLibrary->Request->post('city');
$oUser->email = $this->oLibrary->Request->post('email');
$oUser->setStatus(UserStatus::STATUS_PENDING);
$oUser->create();
$oRequest = new ServiceRequest();
$oRequest->title = $this->oLibrary->Request->post('title');
$oRequest->description = $this->oLibrary->Request->post('description');
$oRequest->user_id = $oUser->id;
$oRequest->setStatus(RequestStatus::STATUS_INCOMPLETE);
$oRequest->create();
// above here goes fine
$oRequestCategory = new RequestCategory();
$oRequestCategory->category_id = $this->oLibrary->Request->post('category');
$oRequestCategory->request_id = $oRequest->id;
$oRequestCategory->create();
我不太明白为什么它不会插入。我已经检查过,request_table
要求的两个密钥都存在于数据库中。当我尝试在Workbench中执行插入时,它会抛出相同的错误,所以我想这是我的数据库设计中的一个缺陷。有人可以向我解释为什么我收到这个外键错误吗?
错误消息本身:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`ruiljedienst`.`request_category`, CONSTRAINT `fk_request_category_category1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
INSERT INTO `ruiljedienst`.`request_category` (`category_id`, `request_id`) VALUES ('1', '1')
这是MySQL工作台中相关数据库表的屏幕截图:
更新
show create table ruiljedienst.request_category
结果:
CREATE TABLE `request_category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`request_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `fk_request_category_category1_idx` (`category_id`),
KEY `fk_request_category_request1_idx` (`request_id`),
CONSTRAINT `fk_request_category_category1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_request_category_request1` FOREIGN KEY (`request_id`) REFERENCES `request` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1'
select id from ruiljedienst.category
这给出了:
答案 0 :(得分:1)
您在category_id
上有外键约束,因此在将行添加到id=1
之前,您必须将category
添加到request_category
表。
确保所有引用的表都使用ENGINE=InnoDB
。