Create a non-standard primary key in Yii 2 migration

If you need a typical primary key then use $this->primaryKey() in your migration file. You can also use something like $this->primaryKey(2), if you need a bigger (here int(2)) primary key.

But, what when you need a non-standard primary key, i.e. you want to turn following example SQL code:

CREATE TABLE `country` (
  `code` CHAR(2) NOT NULL PRIMARY KEY,
  `name` CHAR(52) NOT NULL,
  `population` INT(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

into Yii 2 migration?

Calling:

'code' => $this->primaryKey()->char(2)->notNull()

will fail with error:

Exception: Calling unknown method: yii\db\mysql\ColumnSchemaBuilder::char()

Now, what Qiang?

The solution is quite simple. Create a field (actually: entire table) first, without marking it as a primary key:

$this->createTable('{{%country}}', [
    'code' => $this->char(2)->notNull(),
    'name' => $this->char(52)->notNull(),
    'population' => $this->integer(11)->notNull()->defaultValue(0),
]);

and then simply add one:

$this->addPrimaryKey('pk_on_code', '{{%country}}', 'code');

That would be all folks!

Leave a Reply