我使用 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。
这是错误的图像:
找到答案 :
外键的 引用 必须是其他表中的 主键 。
最佳答案
$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。
关于php - Yii - 使用 migrate 添加外键时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20706030/