Table 添加外键时出现迁移问题
Table migration issue while adding foreign key
我的一个文件包含以下主要内容 table:
public function up()
{
$this->createTable('{{%users}}', [
'id' => 'pk',
'uid'=> 'VARCHAR(150) NOT NULL',
'mydate' => Schema::TYPE_INTEGER . ' NOT NULL',
'state' => "ENUM('INA','ACT') " . ' NOT NULL',
'setting' => Schema::TYPE_INTEGER . ' NOT NULL',
],'ENGINE=InnoDB'
);
}
引用上面table的uid
的childtable是:
$this->createTable('{{%xyztable}}', [
'id'=>'pk',
'uid' => 'integer NOT NULL',
'server_time' => Schema::TYPE_INTEGER . ' NOT NULL',
'answer' => 'VARCHAR(135) NOT NULL',
],'ENGINE=InnoDB'
);
$this->addForeignKey('fk_unique_id',"{{%xyztable}}", 'uid', '{{%users}}', 'uid', 'CASCADE', 'CASCADE');
调用迁移时出现以下错误
Error Info:
Array
(
[0] => HY000
[1] => 1215
[2] => Cannot add foreign key constraint
)
我花了一个多小时也没能搞清楚这个错误。
为了创建外键:
1) 两列应具有相同的类型。
你有不同的类型(字符串和整数):
'uid' => 'VARCHAR(150) NOT NULL',
和
'uid' => 'integer NOT NULL',
2) 在table 外键引用连接列应该有索引。
在您的代码中,这也丢失了。
在迁移中,您可以使用 createIndex() 方法创建索引。
我的一个文件包含以下主要内容 table:
public function up()
{
$this->createTable('{{%users}}', [
'id' => 'pk',
'uid'=> 'VARCHAR(150) NOT NULL',
'mydate' => Schema::TYPE_INTEGER . ' NOT NULL',
'state' => "ENUM('INA','ACT') " . ' NOT NULL',
'setting' => Schema::TYPE_INTEGER . ' NOT NULL',
],'ENGINE=InnoDB'
);
}
引用上面table的uid
的childtable是:
$this->createTable('{{%xyztable}}', [
'id'=>'pk',
'uid' => 'integer NOT NULL',
'server_time' => Schema::TYPE_INTEGER . ' NOT NULL',
'answer' => 'VARCHAR(135) NOT NULL',
],'ENGINE=InnoDB'
);
$this->addForeignKey('fk_unique_id',"{{%xyztable}}", 'uid', '{{%users}}', 'uid', 'CASCADE', 'CASCADE');
调用迁移时出现以下错误
Error Info:
Array
(
[0] => HY000
[1] => 1215
[2] => Cannot add foreign key constraint
)
我花了一个多小时也没能搞清楚这个错误。
为了创建外键:
1) 两列应具有相同的类型。
你有不同的类型(字符串和整数):
'uid' => 'VARCHAR(150) NOT NULL',
和
'uid' => 'integer NOT NULL',
2) 在table 外键引用连接列应该有索引。
在您的代码中,这也丢失了。
在迁移中,您可以使用 createIndex() 方法创建索引。