Php 外键约束失效

Php 外键约束失效,php,mysql,Php,Mysql,我正在编写一个有外键错误的新脚本 我有以下表格:request、category和request\u category 现在在表category中有6个类别,所以这些都很好。 我的脚本将数据插入到request表中,然后尝试向request\u category添加条目,但这就是它失败的地方 守则: $oUser = new User(); $oUser->firstname = $this->oLibrary->Request->post('firstname'); $

我正在编写一个有外键错误的新脚本

我有以下表格:
request
category
request\u category

现在在表
category
中有6个类别,所以这些都很好。 我的脚本将数据插入到
request
表中,然后尝试向
request\u 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_表
所需的两个键。当我尝试在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 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
这使得:


您对
类别\u id
有外键约束,因此必须先将
id=1
添加到
类别
表中,然后再将行添加到
请求\u类别


请确保所有引用的表都使用
ENGINE=InnoDB

,感谢您的快速响应,但类别表中有6个ID为1到6的条目,错误消息称没有。您能否使用
show create table request_category
select id from category
更新您的问题?请尝试在工作台的request_category中创建您的第一条记录,有时您必须在自动生成其余记录之前在auto increment列中添加第一个值。这给我带来了相同的错误:(好吧,你抓住我了,我搞不懂。