完整性约束违规:1062重复“PRIMARY”

时间:2015-07-31 07:07:18

标签: php mysql laravel eloquent laravel-5.1

我想在mysql数据库表中添加多个标签,在这种情况下,当尝试添加单个标签然后它没关系但是当尝试插入多个标签时显示这种类型的错误。这是我的迁移和存储代码。

public function store(CreateArticleRequest $request)
{
    $article = Auth::user()->articles()->create($request->all());

    $article->tags()->attach($request->input('tags'));

    flash()->overlay('Your articles has been created!', 'Good Job');
    return redirect('articles');
}

以下是迁移代码:

public function up()
{

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

    Schema::create('articles_tag',function(Blueprint $table) {
        $table->increments('articles_id')->unsigned()->index();
        $table->foreign('articles_id')->references('id')->on('articles')->onDelete('cascade');

        $table->integer('tag_id')->unsigned()->index();
        $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
        $table->timestamps();
    });
}

以下是刀片中的表单代码标记选择框:

<div class="form-group">
     {!! Form::label('tags','Tags:') !!}
     {!! Form::select('tags[]',$tags,null,['class'=>'form-      control','multiple']) !!}

1 个答案:

答案 0 :(得分:1)

您的迁移错误。表articles_tag是一个数据透视表,因此您无法对该表中的articles_id列使用增量。

要解决此问题,请替换此行:

$table->increments('articles_id')->unsigned()->index();

这一个:

$table->integer('articles_id')->unsigned()->index();