php - 违反完整性约束 : 1062 Duplicate entry '25' for key 'PRIMARY'

标签 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();
    });
}

这是 Blade 中的表单代码标签选择框:

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

最佳答案

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

要解决这个问题,请替换这一行:

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

用这个:

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

关于php - 违反完整性约束 : 1062 Duplicate entry '25' for key 'PRIMARY' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31740080/

相关文章:

python - MySQL 5.6 停止和启动(重新启动)有密码的服务器,在 Windows 7 中,使用 Python

php - Laravel:将上传的文件保存到 session 中

php - 在 Laravel 5 中创建帐户时,如何在数据库中为用户创建现有的表列

php - 查询查找靠近我的地方(Google map )

php - 本地主机拒绝连接重定向

mysql - 我有 2 个表,我试图随机选择另一个表中不存在的值,但我无法让它工作

mysql - Laravel 4 播种口音

php - ZF2如何监听特定controller的dispatch事件

php - 使用 PHP 连接到 WebDAV?

MySQL 2D 排序