这个问题在这里已经有答案了:
mysql创建带有外键的表,给出errno:150(20个答案)
两年前关门了。
我试图通过post表中的key user\u id和user表中的id在post表和user表之间建立一对一的关系。
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('user', [
'id' => $this->integer()->primaryKey(),
'name'=>$this->string(),
'email'=>$this->string()->defaultValue(null),
'password'=>$this->string(),
'isAdmin'=>$this->integer()->defaultValue(0),
'photo'=>$this->string()->defaultValue(null)
]);
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('user');
}
public function up()
{
$this->createTable('post', [
'id' => $this->primaryKey(),
'title'=>$this->string(),
//'description'=>$this->text(),
'content'=>$this->text(),
'date'=>$this->date(),
// 'image'=>$this->string(),
'viewed'=>$this->integer(),
'user_id'=>$this->integer(),
'status'=>$this->integer(),
'category_id'=>$this->integer(),
]);
$this->createIndex(
'idx-post-user_id',
'post',
'user_id'
);
// add foreign key for table `user`
$this->addForeignKey(
'fk-post-user_id',
'post',
'user_id',
'user',
'id',
'CASCADE'
);
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('article');
}
但我错了
add foreign key fk-post-user_id: post (user_id) references user (id)
...Exception 'yii\db\Exception' with message 'SQLSTATE[HY000]: General
error: 1215 Cannot add foreign key constraint The SQL being executed
was: ALTER TABLE `post` ADD CONSTRAINT `fk-post-user_id` FOREIGN KEY
(`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE'
如何建立这种关系?
1条答案
按热度按时间5cg8jx4n1#
尝试使用
'user_id' => $this->integer()->notNull(),