Phinx: Add a primary key on an existing table

Created on 16 Oct 2014  路  11Comments  路  Source: cakephp/phinx

Hello guys,

How we can add a primary key on an existing table ?

I try to do this but the table dont be updated :

    public function up()
    {
        $this->table('toto', array('id' => true))
            ->save();
    }

But Table::update() method was call and this method didn't create primary key ...

bug

Most helpful comment

You should be able to create a primary key by creating an index of type "PRIMARY" just as you can create a unique key. However, the current implementation only looks at the UNIQUE type.

I was expecting $table->addIndex(['someId', 'someOtherId'], ['type' => 'PRIMARY']) to work, but I found out that any index type besides 'unique' is ignored.

With that said: here is my vote for fixing this bug.

All 11 comments

My provisional solution (because i worked with prostresql) :

    public function up()
    {
        $this->execute('ALTER TABLE toto ADD COLUMN id serial PRIMARY KEY');
    }

I would expect addIndex('id', array('primary' => true)) to work, but it won't because primary is not a valid option for table index. Weird.

Voting up for this, though setting unique index on column made mysql's describe output treat it as PRI.

I have exactly the same task and not found any solution except using ALTER TABLE ... :(
But in this case I couldn't use _change()_ method.

You should be able to create a primary key by creating an index of type "PRIMARY" just as you can create a unique key. However, the current implementation only looks at the UNIQUE type.

I was expecting $table->addIndex(['someId', 'someOtherId'], ['type' => 'PRIMARY']) to work, but I found out that any index type besides 'unique' is ignored.

With that said: here is my vote for fixing this bug.

+1

+1

+1

Can we add a method addPrimaryKey()? :)

I think this can be closed now, Table::changePrimaryKey covers this functionality fully, right?

Thats. correct. Thanks for pointing that out @djcvijic

Was this page helpful?
0 / 5 - 0 ratings