Question

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

Was it helpful?

Solution 3

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).

OTHER TIPS

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.

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');
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top