我使用migrate create
创建了迁移,并在其上添加了以下代码:
<?php
class m131220_121449_create_all_tables extends CDbMigration
{
// Use safeUp/safeDown to do migration with transaction
public function safeUp() {
// MEMBERS TABLE
$this->createTable("members", array(
'uniq_id' => 'pk',
'personel_num' => 'int(10) NOT NULL',
'password' => 'string NOT NULL',
'name' => 'string DEFAULT NULL',
'lastupdate' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
), 'ENGINE=InnoDB');
// RESERVED TABLE
$this->createTable("reserved", array(
'uniq_id' => 'pk',
'personel_num' => 'int(10) NOT NULL',
'RsvdDay' => 'date NOT NULL',
'date_created' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
), 'ENGINE=InnoDB');
// Add Foreign Keys Relations for RESERVED
$this->addForeignKey("fk_rsvd_user", "reserved", "personel_num", "members", "personel_num", "CASCADE", "RESTRICT");
}
}
但是当我想要进行此迁移时,我在尝试创建外键时遇到了一般错误#1005。
这是错误的图像:
找到了答案:
外键的引用必须是其他表中的主键。
答案 0 :(得分:5)
$this->createTable("members", array(
'uniq_id' => 'pk',
'personel_num' => 'int(10) NOT NULL',
'password' => 'string NOT NULL',
'name' => 'string DEFAULT NULL',
'lastupdate' => 'timestamp DEFAULT CURRENT_TIMESTAMP',
'UNIQUE KEY `personel_num` (`personel_num`)',
), 'ENGINE=InnoDB');
使personel_num唯一,使其成为外键。您也可以删除uniq_id并将personel_num设为pk。