Doctrine migration foreign keys
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, 开发者_JAVA技巧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
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');
}
}
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).
精彩评论