M
M
Maxim Fedorov2017-10-12 13:14:47
MySQL
Maxim Fedorov, 2017-10-12 13:14:47

Why is ForeignKey not added in migrations?

I am migrating to MySQL in yii2

Migration code:
$this->addColumn('{{%trainer}}', 'studio_id', $this->integer()->notNull());
$this->addForeignKey('fk-trainer-studio', '{{%trainer}}', 'studio_id', '{{%studio}}', 'id', 'CASCADE', 'RESTRICT');


Swears on data integrity. There is a `studio` table, in general I took a similar code from another migration
Mistake:
add foreign key fk-trainer-studio: {{%trainer}} (studio_id) references {{%studio}} (id) ...Exception: 
SQLSTATE[23000]: Integrity constraint violation: 1452 
Cannot add or update a child row: a foreign key constraint fails 
(`db`.`#sql-6cb_105`, CONSTRAINT `fk-trainer-studio` FOREIGN KEY (`studio_id`) REFERENCES `studio` (`id`) ON DELETE CASCADE)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-10-12
@Maksclub

most likely in the table to which you want to add a foreign key there is data that refers to non-existent records

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question