SQL 错误:1452:无法添加或更新子行:外键约束失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5256703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Error: 1452: Cannot add or update a child row: a foreign key constraint fails
提问by Vinay
I have two tables in my database:
我的数据库中有两个表:
order
;course
.
order
;course
.
order
has a column courseid
which references column id
of the course
table. Whenever I tried to do saveAll()
in CakePHP
the above SQL
error will display and data wont be saved.
order
有一列courseid
,其引用列id
的的course
表。每当我试图做saveAll()
在CakePHP
上面的SQL
错误将显示和数据不会被保存。
回答by Nik Chankov
What it sounds is that between your tables you have foreign key constraint in the database. This mean that in the the column course_id you cannot insert values different than ids from the foreign table.
听起来是在您的表之间,您在数据库中有外键约束。这意味着在列 course_id 中,您不能插入与外部表中的 id 不同的值。
The error above means that when you post your data the foreign field is empty or missing.
上面的错误意味着当您发布数据时,外部字段为空或丢失。
What to look for: 1. Check if in your database the foreign field in the child table can accept NULL. If you have dropdown with values and the default option is empty if the field doesn't accept NULL this error could occur 2. Check your data in the controller if you pass the variable in example: $this->data['Order']['course_id'] if it's empty or missing see point 1.
要查找的内容: 1. 检查您的数据库中子表中的外部字段是否可以接受 NULL。如果您有带值的下拉列表,并且如果字段不接受 NULL,则默认选项为空,则可能会发生此错误 2. 如果您在示例中传递变量,请检查控制器中的数据:$this->data['Order'] ['course_id'] 如果它为空或缺失,请参见第 1 点。
回答by WeaponsTheyFear
I am going to respond just for the sake of anyone else with a similar issue looking for an answer. Working with ORM in other frameworks, I made the mistake of trying to assign roles or other data before saving what I was adding a role to. Example:
我只是为了其他有类似问题寻求答案的人而做出回应。在其他框架中使用 ORM 时,我犯了一个错误,即在保存要添加角色的内容之前尝试分配角色或其他数据。例子:
Creating a new user-
创建一个新用户-
$user = ORM::factory('user');
$user->username = 'SomeoneSpecial";
if ($user->add(ORM::factory('role', 'login') && $user->save() ) {
// continue on with code
}
The user is created, however in trying to add the role before the user is saved, you end up with a user without a role and that exact error being spit back out at you.
用户已创建,但是在保存用户之前尝试添加角色时,您最终会得到一个没有角色的用户,并且会向您吐出确切的错误。