简体   繁体   中英

how to alter an existing table column in laravel 5.3 using migrations

I have this:

$table->integer('role_id')->index()->unsigned()->nullable();

But I want to change it to this:

$table->integer('role_id')->index()->unsigned()->nullable()->default(3);

I had wanted to use this, but the source syntax I could not understand:

php artisan make:migration update_role_id_in_users --table=users

I even tried using doctrine/ddbal package and running this:

php artisan make:migration modify_role_id_in_users --table=users

with the migration set up like this:

class ModifyRoleIdInUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //
            $table->integer('role_id')->index()->unsigned()->nullable()->default(3)->change();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
            $table->integer('role_id')->index()->unsigned()->nullable()->change();
        });
    }
}

But I get this error when I go migrate:

[Illuminate\\Database\\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_role_id_index' (SQL: alter table 'users' add index 'users_role_id_index'('role_
id'))

[Doctrine\\DBAL\\Driver\\PDOException] SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_role_id_index'

[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_role_id_index'

How can I alter the column without doing a migrate:refresh

You can use change() method to do this:

$table->integer('role_id')->index()->unsigned()->nullable()->default(3)->change();

Remember to run composer require doctrine/dbal before updating your columns via migrations

Hope this helps!

The solution was to:

  1. run composer require doctrine/ddbal
  2. add the changes I wanted default(3) to the end of the role_id column like this $table->integer('role_id')->index()->unsigned()->nullable()->default(3)->change();
  3. The run php artisan migrate

And that solved it and the table was altered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM