F
F
Flaker2014-06-29 15:45:38
MySQL
Flaker, 2014-06-29 15:45:38

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);

Rank table:
$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');

Gives an error message:
> 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
)

Tell me, what's the problem?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
Pavel Gogolinsky, 2014-07-01
@Flaker

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.

P
phpnt, 2015-03-06
@phpnt


Applying Migrations in Yii2

A
Alexander Zelenin, 2014-06-29
@zelenin

the level field must be the key

T
Torkalas, 2015-10-02
@Torkalas

User table:
add:

$this->createIndex('level','{{%user}}','level', true);
$this->addForeignKey("ranks_fk", "{{%user}}", "level", "{{%ranks}}", "level", 'CASCADE');

Rank table:
replace:
on the :
remove line:
$this->addForeignKey("ranks_fk", "{{%ranks}}", "level", "{{%user}}", "level", 'RESTRICT');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question