完整性约束违规:1452 无法添加或更新子行:外键约束失败

Posted

技术标签:

【中文标题】完整性约束违规:1452 无法添加或更新子行:外键约束失败【英文标题】:Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 【发布时间】:2014-06-24 10:40:30 【问题描述】:

我正在使用 Yii 框架,并且在尝试向表中插入时,数据库出现以下 Yii 错误 - 我可以看到 user_id 为 '5702157058' 的用户存在于我的 'myuser' 表中,所以不知道为什么我收到此错误?

<h1>CDbException</h1>
<p>CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation:       
1452 Cannot add or update a child row: a foreign key constraint fails (`mydb`.`organisation_news_read`, 
CONSTRAINT `FK_organisation_news_read_myuser` FOREIGN KEY (`user_id`) REFERENCES `myuser_`
(`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION). The SQL statement executed was: 
INSERT INTO `organisation_news_read` (`news_id`, `user_id`) VALUES (:yp0, :yp1). 
Bound with :yp0=287, :yp1='5702157058'

【问题讨论】:

【参考方案1】:

请检查以下几点,

1. First check your foreign key field name and its spelling are same.
2. then check your model relation function
3. check your table field are same
4. check the DB engine is it INNODB?

您的外键设置大多有问题。

【讨论】:

【参考方案2】:

检查 'users' 和 'organisation_news_read' 之间的关系,这肯定是问题所在。 试试这个来验证是否存在。

SELECT * FROM users WHERE id = 5702157058;

这应该找到一行。

我认为你的桌子是这样的。 (顺便说一下,这个例子在 postgres 中)

CREATE TABLE users
(
  id serial NOT NULL,
  name character varying(50),
  last_name character varying(50),
  CONSTRAINT pk_users PRIMARY KEY (id)
)



CREATE TABLE organisation_news_read
(
  id serial NOT NULL,
  users_id integer,
  CONSTRAINT pk_organisation PRIMARY KEY (id),
  CONSTRAINT fk_organisation_vs_users FOREIGN KEY (users_id)
      REFERENCES users (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

希望对你有帮助

【讨论】:

以上是关于完整性约束违规:1452 无法添加或更新子行:外键约束失败的主要内容,如果未能解决你的问题,请参考以下文章

SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败

完整性约束违规:1452 无法添加或更新子行:外键约束失败(Laravel 应用程序)

SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败 - Laravel

:完整性约束违规:1452 无法添加或更新子行:laravel 迁移中的外键约束失败

SQL 错误:SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败 - Laravel