views:

432

answers:

3

In PHP Doctrine, is it possible to create one migration class that creates a table and creates a foreign key on that table? For some reason, I can't get the foreign key to work ...

class Migration_001 extends Doctrine_Migration_Base {
    public function up() {
        $this->createTable('table_name', array(...))
        $this->createForeignKey('table_name', 'foreign_key_name', array(...))
    }

    public function down() {
        $this->dropForeignKey('table_name', 'foreign_key_name')
        $this->dropTable('table_name')
    }
}

Thanks, Ofir

A: 

This might not be a definitive answer, but I've noticed that if you use the CLI to create migrations from an existing schema, Doctrine will generate a separate migration to create each table and then generate a final single migration that sets up all the foreign key relations.

I would try moving the foreign key creation into a separate migration and see if that works.

Bryan M.
A: 

you need to add the 'foreign_key_name' index before you can add the foreign key constraint on it. so:

class Migration_001 extends Doctrine_Migration_Base {

    public function up() {

        $this->createTable('table_name', array(...));
        $this->addIndex('table_name', 'foreign_key_name', array(
             'fields'=>array('local_id')
        ));
        $this->createForeignKey('table_name', 'foreign_key_name', array(
             'local' => 'local_id',
             'foreign' => 'id',
             'foreignTable' => 'foreign_table',
             'onDelete'=>'CASCADE'
        ));
    }

    public function down() {
        $this->dropForeignKey('table_name', 'foreign_key_name');
        $this->removeIndex('table_name', 'foreign_key_name');
        $this->dropTable('table_name');
    }
}
dao777
As far as I know, Doctrine creates the index automatically. I've never had to create an index prior to adding a foreign key. I guess I had another problem there with the fields not being identical or a data that was wrong in the table or something of that sort. Since then, I was able to create a table and a foreign key in the same migration class ... problem was solved, and the answer to my own question is "yes we can!" :)
Ofir
A: 

To answer my own question, the answer is yes.

You do have to check that everything is in order, though, meaning that the columns should be identical (type, length, etc.) and also that the foreign key is a unique key in his own table (I don't remember but maybe it should also be the first column).

Ofir