简体   繁体   English

违反完整性约束:1452 无法添加或更新子行:

[英]Integrity constraint violation: 1452 Cannot add or update a child row:

I am trying to insert values into my comments table and I am getting a error.我正在尝试将值插入到我的评论表中,但出现错误。 Its saying that I can not add or update child row and I have no idea what that means.它说我不能添加或更新子行,我不知道这意味着什么。

my schema looks something like this我的架构看起来像这样

-- ----------------------------
-- Table structure for `comments`
-- ----------------------------
DROP TABLE IF EXISTS `comments`;
CREATE TABLE `comments` (
  `id` varchar(36) NOT NULL,
  `project_id` varchar(36) NOT NULL,
  `user_id` varchar(36) NOT NULL,
  `task_id` varchar(36) NOT NULL,
  `data_type_id` varchar(36) NOT NULL,
  `data_path` varchar(255) DEFAULT NULL,
  `message` longtext,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_comments_users` (`user_id`),
  KEY `fk_comments_projects1` (`project_id`),
  KEY `fk_comments_data_types1` (`data_type_id`),
  CONSTRAINT `fk_comments_data_types1` FOREIGN KEY (`data_type_id`) REFERENCES `data_types` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_comments_projects1` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_comments_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf32;

-- ----------------------------
-- Records of comments
-- ----------------------------

-- ----------------------------
-- Table structure for `projects`
-- ----------------------------
DROP TABLE IF EXISTS `projects`;
CREATE TABLE `projects` (
  `id` varchar(36) NOT NULL,
  `user_id` varchar(36) NOT NULL,
  `title` varchar(45) DEFAULT NULL,
  `description` longtext,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_projects_users1` (`user_id`),
  CONSTRAINT `fk_projects_users1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf32;

-- ----------------------------
-- Records of projects
-- ----------------------------
INSERT INTO `projects` VALUES ('50dcbc72-3410-4596-8b71-0e80ae7aaee3', '50dcbc5c-d684-40bf-9715-0becae7aaee3', 'Brand New Project', 'This is a brand new project', '2012-12-27 15:24:02', '2012-12-27 15:24:02');

and the mysql statement I am trying to do looks something like this我试图做的 mysql 语句看起来像这样

INSERT INTO `anthonyl_fbpj`.`comments` (`project_id`, `user_id`, `task_id`, `data_type_id`, `message`, `modified`, `created`, `id`) 
VALUES ('50dc845a-83e4-4db3-8705-5432ae7aaee3', '50dcbc5c-d684-40bf-9715-0becae7aaee3', '1', '50d32e5c-abdc-491a-a0ef-25d84e9f49a8', 'this is a test', '2012-12-27 19:20:46', '2012-12-27 19:20:46', '50dcf3ee-8bf4-4685-aa45-4eb4ae7aaee3')

the error I get looks like this我得到的错误看起来像这样

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( anthonyl_fbpj . comments , CONSTRAINT fk_comments_projects1 FOREIGN KEY ( project_id ) REFERENCES projects ( id ) ON DELETE NO ACTION ON UPDATE NO ACTION) SQLSTATE [23000]:完整性约束违规:1452不能添加或更新子行,外键约束失败( anthonyl_fbpjcomments ,约束fk_comments_projects1外键( project_id )参考projectsid )ON DELETE NO ACTION ON UPDATE NO ACTION)

It just simply means that the value for column project_id on table comments you are inserting doesn't exist on table projects .这只是意味着您插入的表comments上的列project_id的值在表projects中不存在。 Bear in mind that the values of column project_id on table comments is dependent on the values of ID on table Projects .请记住,表comments上的project_id列的值取决于表Projects上的ID值。

The value 50dc845a-83e4-4db3-8705-5432ae7aaee3 you are inserting for column project_id does not exist on table projects .您为列project_id插入的值50dc845a-83e4-4db3-8705-5432ae7aaee3在表projects中不存在。

Make sure you have project_id in the fillable property of your Comment model.确保您的Comment模型的fillable属性中有project_id

I had the same issue, And this was the reason.我有同样的问题,这就是原因。

If you are adding new foreign key to an existing table and the columns are not null and not assigned default value, you will get this error,如果您向现有表添加新外键并且列不为空且未分配默认值,您将收到此错误,

Either you need to make it nullable or assign default value , or delete all the existing records to solve it.您需要使其nullableassign default value ,或者delete all the existing records来解决它。

还要确保您添加的外键与原始列的类型相同,如果您引用的列不是相同的类型,它也会失败。

I hope my decision will help.我希望我的决定会有所帮助。 I had a similar error in Laravel.我在 Laravel 中也有类似的错误。 I added a foreign key to the wrong table.我在错误的表中添加了外键。
Wrong code:错误的代码:

Schema::create('comments', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index()->nullable();
...
$table->foreign('post_id')->references('id')->on('comments')->onDelete('cascade');
    });


Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    ...
    });

Please note to the function on('comments') above.请注意上面的 on('comments') 函数。 Correct code正确的代码

 $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

that means that the value for column project_id on table comments you are inserting not only doesn't exist on table projects BUT also project_id probably doesn't have default value .这意味着,对于列值project_id表上comments ,你不仅将doesn't exist于表项目,而且project_id可能没有默认值 Eg in my case I set it as NULL.例如,在我的情况下,我将其设置为 NULL。

As for Laravel you can consider this expressions as a chunk of code of a migration php file, for example:对于 Laravel,您可以将此表达式视为迁移 php 文件的一段代码,例如:

class ForeinToPhotosFromUsers extends Migration

{ /** * Run the migrations. * * @return void */

public function up()
{
    Schema::table('users', function (Blueprint $table) {
    $table->unsignedBigInteger('photo_id')->nullable();// ! ! ! THIS STRING ! ! !
    $table->foreign('photo_id')->references('id')->on('photos');
});
}

}

Obviously you had to create the Model class(in my case it was Photo) next to all these.显然,您必须在所有这些旁边创建 Model 类(在我的例子中是 Photo)。

First delete the constraint "fk_comments_projects1" and also its index.首先删除约束“fk_comments_projects1”及其索引。 After that recreate it.之后重新创建它。

Maybe you have some rows in the table that you want to create de FK.也许您想要创建 de FK 表中的一些行。

Run the migration with foreign_key_checks OFF Insert only those records that have corresponding id field in contents table.使用 foreign_key_checks OFF 运行迁移仅插入那些在内容表中具有相应 id 字段的记录。

You also get this error if you do not create and populate your tables in the right order.如果您没有以正确的顺序创建和填充表,您也会收到此错误。 For example, according to your schema, Comments table needs user_id , project_id , task_id and data_type_id .例如,根据您的架构, Comments 表需要user_idproject_idtask_iddata_type_id This means that Users table, Projects table, Task table and Data_Type table must already have exited and have values in them before you can reference their ids or any other column.这意味着Users表、 Projects表、 Task表和Data_Type必须已经退出并在其中包含值,然后才能引用它们的 id 或任何其他列。

In Laravel this would mean calling your database seeders in the right order:在 Laravel 中,这意味着以正确的顺序调用数据库播种机:

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserSeeder::class);
        $this->call(ProjectSeeder::class);
        $this->call(TaskSeeder::class);
        $this->call(DataTypeSeeder::class);
        $this->call(CommentSeeder::class);
    }
}

This was how I solved a similar issue.这就是我解决类似问题的方法。

In case someone is using Laravel and is getting this problem.如果有人正在使用 Laravel 并遇到此问题。 I was getting this as well and the issue was in the order in which I was inserting the ids (ie, the foreign keys) in the pivot table.我也遇到了这个问题,问题出在我在数据透视表中插入 ID(即外键)的顺序。

To be concrete, find below an example for a many to many relationship:具体来说,请在下面找到多对多关系的示例:

wordtokens <-> wordtoken_wordchunk <-> wordchunks wordtokens <-> wordtoken_wordchunk <-> wordchunks

// wordtoken_wordchunk table
Schema::create('wordtoken_wordchunk', function(Blueprint $table) {
        $table->integer('wordtoken_id')->unsigned();
        $table->integer('wordchunk_id')->unsigned();

        $table->foreign('wordtoken_id')->references('id')->on('word_tokens')->onDelete('cascade');
        $table->foreign('wordchunk_id')->references('id')->on('wordchunks')->onDelete('cascade');

        $table->primary(['wordtoken_id', 'wordchunk_id']);
    });

// wordchunks table
Schema::create('wordchunks', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('text');
    });

// wordtokens table
Schema::create('word_tokens', function (Blueprint $table) {
        $table->increments('id');
        $table->string('text');
});

Now my models look like follows:现在我的模型如下所示:

class WordToken extends Model
{
   public function wordchunks() {
      return $this->belongsToMany('App\Wordchunk');
   }
}

class Wordchunk extends Model
{

    public function wordTokens() {
        return $this->belongsToMany('App\WordToken', 'wordtoken_wordchunk', 'wordchunk_id', 'wordtoken_id');
    }
}

I fixed the problem by exchanging the order of 'wordchunk_id' and 'wordtoken_id' in the Wordchunk model.我通过交换 Wordchunk 模型中 'wordchunk_id' 和 'wordtoken_id' 的顺序解决了这个问题。

For code completion, this is how I persist the models:对于代码完成,这就是我坚持模型的方式:

private function persistChunks($chunks) {
    foreach ($chunks as $chunk) {
        $model = new Wordchunk();
        $model->text = implode(' ', array_map(function($token) {return $token->text;}, $chunk));
        $tokenIds = array_map(function($token) {return $token->id;}, $chunk);
        $model->save();
        $model->wordTokens()->attach($tokenIds);
    }
}

I had this issue when I was accidentally using the WRONG "uuid" in my child record.当我不小心在我的子记录中使用了错误的“uuid”时,我遇到了这个问题。 When that happens the constraint looks from the child to the parent record to ensure that the link is correct.当这种情况发生时,约束会从子记录到父记录,以确保链接正确。 I was generating it manually, when I had already rigged my Model to do it automatically.当我已经操纵我的模型来自动生成它时,我是手动生成的。 So my fix was:所以我的解决方法是:

$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent

Then when I called my child class to insert children, I passed this var value:然后当我调用我的子类来插入子类时,我传递了这个 var 值:

$parent->uuid

Hope that helps.希望有帮助。

I had the same error, the problem was that I was trying to add role_id foreign to the users table, but role_id did not have a default value, so the DB did not allow me to insert the column because I already had some users and it didn't know how to add the column to them.我遇到了同样的错误,问题是我试图将role_id外部添加到users表中,但是role_id没有默认值,因此数据库不允许我插入该列,因为我已经有一些用户并且它不知道如何向他们添加列。 Since I was in development I just used migrate:fresh , but if I was on production, I would probably set a default value to the role_id and not make it not constrained until I had the corresponding role on the DB.由于我在开发中,我只使用了migrate:fresh ,但如果我在生产中,我可能会为role_id设置一个默认值,并且在我在数据库上拥有相应的角色之前不会使其不受约束。

可能是您插入的外键值与主键的值不匹配。

问题可能是因为在您尝试添加的具有 project_id 的数据库中找不到项目记录...

I had a table fulfilled with some entries that has dead foreigners keys.我有一张桌子,里面装满了一些带有死外国人钥匙的条目。 once i cleaned the table, i was able to add a new constraint.一旦我清理了桌子,我就能够添加一个新的约束。

DELETE FROM `table_with_bad_entries` WHERE `expected_foreign_key` not in (select `id` from `the_referenced_table`);

就我而言,它不起作用,因为我在模型中的其中一个名称中留了一个空格,请在此处输入图像描述

I just exported the table deleted and then imported it again and it worked for me.我只是导出删除的表,然后再次导入它,它对我有用。 This was because i deleted the parent table(users) and then recreated it and child table(likes) has the foreign key to parent table(users).这是因为我删除了父表(用户),然后重新创建它,子表(喜欢)具有父表(用户)的外键。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel-违反完整性约束:1452无法添加或更新子行 - Laravel - Integrity constraint violation: 1452 Cannot add or update a child row 违反完整性约束 - 1452 无法添加或更新子行 - Integrity constraint violation - 1452 Cannot add or update a child row SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败 - SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 违反完整性约束:1452无法添加或更新子行:外键约束失败 - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 违反完整性约束:1452无法添加或更新子行:外键约束失败 - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel 5:违反完整性约束:1452 无法添加或更新子行:外键约束失败 - Laravel 5: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel 5.2 - 违反完整性约束:1452 无法添加或更新子行:外键约束失败 - Laravel 5.2 - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Laravel:SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败 - Laravel: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败 - SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:Laravel 5中的外键约束失败 - SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails in Laravel 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM