Add new value to an enum type field in Laravel

6

I am working with migrations in Laravel and I have a partners table that has a type attribute of type enum with the following values:

$table->enum('type', ['cliente', 'proveedor', 'empleado', 'transportadora'])->nullable();

What I need is the following: Create another migration so that you can modify the partners table, adding a value to the enum so that the database is as follows:

['cliente', 'proveedor', 'empleado', 'transportadora', 'nuevo_dato']

What I tried so far was the following:

Schema::table('partners', function ($table) {            
         DB::statement("ALTER COLUMN 'type' ADD VALUE 'nuevo_dato' AFTER 'cliente'");
});

And I also tried:

Schema::table('partners', function ($table) {    
      $table->enum('type', ['cliente', 'proveedor', 'empleado', 'transportadora', 'nuevo_dato'])->change();
});

And ...

DB::statement("ALTER TABLE 'partners' MODIFY COLUMN 'type' enum('nuevo_dato') NOT NULL AFTER 'transportadora'");

Without reaching the expected result. I would appreciate it if you would help me with this. (PS: I'm using PostgreSQL)

    
asked by MarianoC1993 30.08.2018 в 22:40
source

1 answer

3

The documentation explains how to make the changes using doctrine/dbal ( Modifying Columns ) but clarifies that is not supported for columns of type enum .

Particularly I try to avoid the columns of type enum and handle the options from the application, but I can think of a way to solve your problem that even though some steps should solve your problem.

1º Make a backup of the database.

In the migration

public function up()
{
    // Generá una nueva columna igual a 'type'
    Schema::table('partners', function ($table) {    
          $table->enum('type2', ['cliente', 'proveedor', 'empleado', 'transportadora'])->nullable();
    });

    // Copiá los datos de la columna 'type' a la columna 'type2' 
    \DB::raw('UPDATE 'partners' SET type2=type');

    // Eliminá la columna 'type' y volvé a generarla con la nueva definición
    Schema::table('partners', function (Blueprint $table) {
        $table->dropColumn(['type']);
        $table->enum('type', ['cliente', 'proveedor', 'empleado', 'transportadora', 'nuevo_dato']);
    });

    // Volvé a copiar los datos  
    \DB::raw('UPDATE 'partners' SET type=type2'); 

    // y luego eliminá la columna 'type2' 
    Schema::table('partners', function (Blueprint $table) {
        $table->dropColumn([type2']);
    });
}

The truth is that I never did something like that but it should work. I await your comment and remember to DO A BACKUP of the BD BEFORE doing anything, especially if you are in production. I recommend you clone the base in your local environment and run the migration and verify that it works before running the migration in production.

    
answered by 31.08.2018 / 02:20
source