我正在编写一个有外键错误的新脚本。
我有以下表格: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
要求存在于数据库中。当我尝试在工作台中进行插入时,它会抛出相同的错误,所以我猜这是我的数据库设计中的某个缺陷。有人可以向我解释为什么我会收到此外键错误吗?
错误消息本身:
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 Workbench 中相关数据库表的屏幕截图:
更新:
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
这给出:
最佳答案
您对 category_id
有外键约束,因此您必须在添加行之前将 id=1
添加到 category
表中到request_category
。
确保所有引用的表都使用 ENGINE=InnoDB
。
关于php - 外键约束失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889232/