Laravel 5:违反完整性约束:1062-多对多 [英] Laravel 5: Integrity constraint violation: 1062 - Many to Many

查看:189
本文介绍了Laravel 5:违反完整性约束:1062-多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以下建议.

我有2次迁移,就像这样.

I have 2 migrations, like so.

        Schema::create('plates', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('serial_number');
        $table->string('crc-code', 50);
        $table->string('reason', 50)->nullable();

        $table->softDeletes();

        $table->timestamps();
    });

还有一个

  Schema::create('documents', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 25)->unique();
        $table->text('description')->nullable();
        $table->longText('relative_path');

像这样设置的用于许多关系的数据透视表

A pivot table for many to many relations I have setup just like this

        Schema::create('document_plate', function (Blueprint $table) {
      $table->integer('plate_id')->unsigned()->index();
      $table->integer('document_id')->unsigned()->index();

      $table->primary(['plate_id', 'document_id']);

      $table->timestamps();
    });

采取某种措施时,我使用下面的代码将plate附加到document

When taking a certain action I use the code below to attach a plate to a document

       $plate  =   Plate::find(1);
       $doc    =   Document::find(1);
       if($plate && $doc) {
          $plate->documents()->attach($doc->id);
       }

第一次,一切正常! document_plate得到更新.当再次使用相同的ids进行操作时,会发生该错误.

The first time, everything works just fine! the document_plate gets updated. The error occurs when having the same ids doing it again.

SQLSTATE [23000]:违反完整性约束:1062重复了键"PRIMARY"的条目"1-1"(SQL:插入到document_plate(created_atdocument_idplate_idupdated_at)中

现在问题

有没有一种避免出错的方法,只是使用相同的ids更新表?

Is there a way to avoid getting errors and just update the table with the same ids??

或者..我需要在前端设置某种验证,以告知用户(提交之前)他/她选择了表中已经存在的相同id's.

Or.. I need to setup a some sort of validation on the front-end which tells the user (before submitting) that he/she choose the same id's which are already in the table.

注意:我正在使用AngularJS进行前端操作.

Note: I am using AngularJS for front-end operations.

推荐答案

Laravel通过使用sync方法非常简单地实现了这一点. sync方法默认情况下将分离您没有传递给它的所有id,但是它接受第二个参数可以禁用分离.

Laravel makes this very simple to achieve by using the sync method. The sync method by default will detach any ids that you don't pass to it, but it accepts a second argument that can disable the detaching.

$plate->documents()->sync([$doc->id], false);

仅当表中尚不存在该条目时,才会添加该条目.

This will only add the entry if it does not already exist in the table.

链接到API: http://laravel .com/api/5.1/Illuminate/Database/Eloquent/Relations/BelongsToMany.html#method_sync

这篇关于Laravel 5:违反完整性约束:1062-多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆