将新的自动增量列添加到现有表 [英] Add new auto increment column to existing table

查看:59
本文介绍了将新的自动增量列添加到现有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前的迁移是:

Schema::create('item_tag', function (Blueprint $table) {

    $table->integer('item_id')->unsigned()->index();
    $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');

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

    $table->primary(['item_id', 'tag_id']);

});

现在我要为此添加新的自动增量列并删除旧的主键

Now I want add new auto increment column to this and drop old primary key

我尝试:

Schema::table('item_tag', function (Blueprint $table) {

    $table->unsignedInteger('id', true)->first();

    $table->dropPrimary();
    $table->primary('id');

});

但是在迁移后会出现错误:

But it have a error after migrate:

SQLSTATE [42000]:语法错误或访问冲突:1068多个主键已定义

SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined

推荐答案

将主键拖放到单独的迁移中,然后删除 $ table-> primary('id').添加 AUTO_INCREMENT 列会自动创建一个主键:

Drop the primary key in a separate migration and remove $table->primary('id'). Adding an AUTO_INCREMENT column automatically creates a primary key:

Schema::table('item_tag', function (Blueprint $table) {   
    $table->dropPrimary();
});

Schema::table('item_tag', function (Blueprint $table) {
    $table->unsignedInteger('id', true)->first();
});

您还可以简化第二次迁移:

You can also simplify the second migration:

Schema::table('item_tag', function (Blueprint $table) {
    $table->increments('id')->first();
});

这篇关于将新的自动增量列添加到现有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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