How do I Implement AUTO_INCREMENT in a Yii2 Migration Using MySQL?

Why not a simply primaryKey?, the format for integer(8) , integer(11) or primary key is always the same is always an integer long then or you need a small int (max 5 digit) or you can use the normal $this->primaryKey() because

SMALLINT is for storage of 2 byte (value -32768 32767) an then smallInteger(8) is not coherent. the numer 8 is for output not for store format. If you want 8 digit you need at least INT of 4 byte -2147483648 2147483647 or more


    $this->createTable('posts', [

        'post_id' => "bigint(20) unsigned NOT NULL AUTO_INCREMENT",

        'loc_id' => $this->integer(10)->unsigned()->notNull(),

        "PRIMARY KEY (`post_id`,`loc_id`)",

    ], 'ENGINE=InnoDB DEFAULT CHARSET=utf8');

If it is critical to have that column type, you can always change it:

$this->createTable('{{%status}}', [
    'id'          => $this->primaryKey(11),
    'description' => $this->string(20),
]);
$this->alterColumn('{{%status}}', 'id', $this->smallInteger(8).' NOT NULL AUTO_INCREMENT');

(I've tested this with MySQL - it works)

However, like @scaisEdge says, it's usually not worth the troble.


This works for me

$this->createTable('new_table',[
        'id' => Schema::TYPE_PK.' NOT NULL AUTO_INCREMENT',
        'name' => Schema::TYPE_STRING,
        'age' => Schema::TYPE_INTEGER
    ]);

However you can simply use the below style and Yii will replace the 'pk' type of id based on your DBMS. for MYSQL it will be int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY

$this->createTable('new_table',[
        'id' => 'pk',
        'name' => Schema::TYPE_STRING,
        'age' => Schema::TYPE_INTEGER
    ]);

Tags:

Mysql

Php

Yii2