Create a primary key column using migration

I use migrations in Yii to create a new column. My code works fine however, I'm not sure how to set the primary key?

This is part of my migration file:

public function up()
{
    $this->addColumn(
        'competition_prizes',
        'prize_id',
        'INT(11) UNSIGNED NOT NULL FIRST',
    );

    $this->addPrimaryKey('PK1', 'competition_prizes', 'prize_id');
}

I do not know how to make a competition_prizesprimary key column.

+3
source share
5 answers

Now it works - did the following:

$this->addColumn(
    'competition_prizes',
    'prize_id',
    'INT(11) UNSIGNED NOT NULL AUTO_INCREMENT primary key FIRST'
);
+1
source

After your function addColumnadds this line

$this->addPrimaryKey('PK1', 'competition_prizes', 'prize_id')

Make sure the table does not have a primary key column.

+4
source

Yii2 2.0.6 - http://www.yiiframework.com/doc-2.0/yii-db-schemabuildertrait.html#primaryKey%28%29-detail

$this->createTable('sometable', [
    'sometable_id' => $this->primaryKey(), // does not depend on Your DBMS
    'sometable_number' => 'SMALLINT(6) UNSIGNED NULL DEFAULT NULL'// will be depend on your DBMS.
]);
+1

$this->addColumn('competition_prizes', 'prize_id', 'pk');

'pk' translates to 'int (11) NOT NULL AUTO_INCREMENT PRIMARY KEY' Yii2 QueryBuilder Column Type

0
source

Use the constructor. At the beginning of the file, add

use yii\db\Schema; 

And then add:

$this->addColumn(
    'competition_prizes'=> Schema::TYPE_PK,
    'prize_id'=> Schema::TYPE:INTEGER,
);
0
source

All Articles