使用laravel中的迁移删除主键并在数据库中自动增加

时间:2017-06-09 06:55:09

标签: php laravel artisan

我有主键和自动增量字段的表,我想要进行新的迁移以删除主键索引并删除自动增量字段。我怎样才能做到这一点。

我创建了新的迁移

public function up()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->unsignedInteger('message_id');
    });
}

它给我的命令错误为[Illuminate\Database\QueryException]
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'message _id' (SQL: alter table tbl_'message_read_state' add 'message_id' int unsigned not null)

什么错了?????

7 个答案:

答案 0 :(得分:9)

Blueprint类提供了dropPrimary方法,允许您删除主键。

public function down()
{
    Schema::table('table', function (Blueprint $table) {
        $table->dropPrimary();
        $table->unsignedInteger('id'); // for removing auto increment

    });
}

答案 1 :(得分:3)

你可以试试这个

$table->dropPrimary('id_primary');

答案 2 :(得分:2)

删除主键:

$table->dropPrimary( 'id' );

Reference

答案 3 :(得分:1)

使用简单的删除列

$table->dropColumn('id');

答案 4 :(得分:1)

dropPrimary方法只删除了主键,而不是列。你必须这样做:

    /**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->dropColumn('message_id');
        $table->unsignedInteger('message_id');
    });
}

或者不是删除并重新创建列,而是可以在Laravel 5中使用change

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->integer('message_id')->unsigned()->change();
    });
}

答案 5 :(得分:0)

这对我有用:

Schema::table('table_name', function (Blueprint $table) {
    // Make AI field `id` unsigned otherwise SQL 
    // will throw error when you try to remove it
    $table->integer('id')->unsigned()->change();

    $table->dropColumn('id');

    // If there was a foreign on message_id, make sure to remove it
    $table->dropForeign('table_name_message_id_foreign');

    $table->dropPrimary('message_id');
    $table->dropColumn('message_id');
}

答案 6 :(得分:-2)

https://laravel.com/docs/4.2/schema#dropping-indexes

  1. tabel_name
  2. index $table->dropPrimary('users_id_primary');