简体   繁体   English

教义迁移外键

[英]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? 在PHP Doctrine中,是否可以创建一个迁移类来创建表并在该表上创建外键? 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 谢谢,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. 这可能不是一个明确的答案,但是我注意到,如果您使用CLI从现有模式创建迁移,Doctrine将生成一个单独的迁移来创建每个表,然后生成最终的单个迁移来设置所有外部表。关键关系。

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. 您需要先添加“ foreign_key_name”索引,然后才能对其添加外键约束。 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). 但是,您必须检查所有内容是否井井有条,这意味着各列应该相同(类型,长度等),并且外键是他自己的表中的唯一键(我不记得了,但也许它也应该是第一列)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM