Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a 'enum' MySQL field type with Phinx Migrate

I'm trying to create a migration in Phinx (actually a rollback) which will create a enum type field in a MySQL DB. Having read the docs I was under the impression that this should be pretty simple but it just fails every time.

$table = $this->table('mytable');
$table->addColumn('warmth','enum', array('limit' => array('1', '2', '3', '4', '5', 'P', 'A', 'B', 'C', 'D', 'X', 'N')))
->save();

Unfortunately there's no easy way to have Phinx output the offending SQL query either.

like image 818
Nathan Pitman Avatar asked Mar 02 '16 12:03

Nathan Pitman


People also ask

How do you add an ENUM to a field?

You can add a new value to a column of data type enum using ALTER MODIFY command. If you want the existing value of enum, then you need to manually write the existing enum value at the time of adding a new value to column of data type enum.

How do I declare an ENUM in MySQL?

ENUM values are sorted based on their index numbers, which depend on the order in which the enumeration members were listed in the column specification. For example, 'b' sorts before 'a' for ENUM('b', 'a') . The empty string sorts before nonempty strings, and NULL values sort before all other enumeration values.

How ENUM values are stored in MySQL?

As explained here, enums are stored as values between 0 (no valid value set) and 65,535 that are associated with an enumeration index. The value that is stored in the table is a 2 byte value, not a string.

Does MySQL support ENUM?

In MySQL, an ENUM is a string object whose value is chosen from a list of permitted values defined at the time of column creation. The ENUM data type provides the following advantages: Compact data storage. MySQL ENUM uses numeric indexes (1, 2, 3, …) to represents string values.


2 Answers

Use latest version from master (above 0.5.x-dev):

$this->table('my_table')
->addColumn('status', 'enum', ['values' => ['enabled', 'disabled']])
->save();
like image 148
hshhhhh.name Avatar answered Oct 17 '22 06:10

hshhhhh.name


Maybe for others it will be interesting that there is another way to add an ENUM column

use Phinx\Db\Adapter\MysqlAdapter;
use Phinx\Db\Table\Column;

$this->table('posts')
    ->addColumn(
        (new Column())
            ->setName('status')
            ->setType(MysqlAdapter::PHINX_TYPE_ENUM)
            ->setValues([
                'draft', 'publish', 'private', 'trash',
            ])
    )
    ->update();
like image 2
Serhii Andriichuk Avatar answered Oct 17 '22 05:10

Serhii Andriichuk