Answer the question
In order to leave comments, you need to log in
How to add Foreign Key to MySQL table?
I'm trying to link 2 tables, user and rank table.
In Yii2 migrations, in order:
User table:
$this->createTable('{{%user}}', [
'id' => Schema::TYPE_INTEGER . ' NOT NULL AUTO_INCREMENT',
'username' => Schema::TYPE_STRING . ' NOT NULL',
'level' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 1',
'PRIMARY KEY (id)',
], $tableOptions);
$this->createTable('{{%ranks}}', [
'level' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 1',
'rank' => Schema::TYPE_STRING . ' NOT NULL',
'exp' => Schema::TYPE_INTEGER . ' NOT NULL'
], $tableOptions);
$this->addForeignKey("ranks_fk", "{{%ranks}}", "level", "{{%user}}", "level", 'RESTRICT');
> add foreign key ranks_fk: {{%ranks}} (level) references {{%user}} (level) ...Exception 'yii\db\Exception' with message 'SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
The SQL being executed was: ALTER TABLE `ranks` ADD CONSTRAINT `ranks_fk` FOREIGN KEY (`level`) REFERENCES `user` (`level`) ON DELETE RESTRICT'
in C:\OpenServer\domains\site-dev\vendor\yiisoft\yii2\db\Schema.php:503
Error Info:
Array
(
[0] => HY000
[1] => 1215
[2] => Cannot add foreign key constraint
)
Answer the question
In order to leave comments, you need to log in
1) Fields must be keys. In the User table, index the level field (phpmyadmin has a button with a lightning bolt "Index")
2) The fields must be the same in type and in terms of restrictions. If the first field is an Integer with a limit of 11 characters, then the second field must be an Integer of 11 characters.
User table:
add:
$this->createIndex('level','{{%user}}','level', true);
$this->addForeignKey("ranks_fk", "{{%user}}", "level", "{{%ranks}}", "level", 'CASCADE');
$this->addForeignKey("ranks_fk", "{{%ranks}}", "level", "{{%user}}", "level", 'RESTRICT');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question