3

I am using migrations in Yii to create a new column with. My code works fine however, I am unsure how to set a primary key?

This is a part from 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 don't know, how to make competition_prizes column the primary key.

trejder
  • 17,148
  • 27
  • 124
  • 216
Zabs
  • 13,852
  • 45
  • 173
  • 297

5 Answers5

4

After your addColumn function add this line

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

Make sure there is no primary key column in your table.

Kumar V
  • 8,810
  • 9
  • 39
  • 58
  • I'm getting an error - am I doing something wrong-i've modified my original post above. The error is :-unexpected ')' on line 11 - this is the line with the addPrimaryKey bit – Zabs Jan 31 '14 at 16:41
  • 1
    I think last ',' in your addColumn(). Remove that last `,` – Kumar V Jan 31 '14 at 16:45
  • Superb! Almost there... is it possible to setup AUTO INCREMENT om the the primary key? At the moment the column goes in but it doesn't add increment the value for the primary key by 1 each time. – Zabs Jan 31 '14 at 16:48
  • 1
    please check this url. I'm using this link in my projestc. ypu will get all here. http://www.yiiframework.com/doc/api/1.1/CDbMigration#addColumn-detail – Kumar V Jan 31 '14 at 16:52
  • Cheers will give that a shot – Zabs Jan 31 '14 at 16:53
2

This is working now - did the following:

$this->addColumn(
    'competition_prizes',
    'prize_id',
    'INT(11) UNSIGNED NOT NULL AUTO_INCREMENT primary key FIRST'
);
Zabs
  • 13,852
  • 45
  • 173
  • 297
1

For Yii2 version 2.0.6 - Take a look at 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.
]);
0

you can also do this

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

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

Michael Nguyen
  • 1,691
  • 2
  • 18
  • 33
0

Use constructer. At the begining of file add

use yii\db\Schema; 

And then add:

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