Olga
Olga

Reputation: 443

Yii2 - migration, a foreign key constraint fails

I use migration, created up() like that:

$this->addColumn('presentation_place', 'user_id', $this->integer()->notNull()->after('post_code'));
$this->addForeignKey('fk_presentation_place_user_id', 'presentation_place', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE');

And while yii/migrate I'm getting error

Cannot add or update a child row: a foreign key constraint fails ('crm'.'#sql-1524_46f', CONSTRAINT 'fk_presentation_place_user_id' FOREIGN KEY ('user_id') REFERENCES 'user' ('id') ON DELETE CASCADE ON UPDATE CASCADE)

I don't know what can be wrong, I've done migrations couple of times before, so I'm really surprised.

Upvotes: 1

Views: 1586

Answers (1)

From the error message I think that the foreign key add was successful, but you have rows in user and presentation_place.

Try running this migration with empty tables or set a default value which exists in the referenced table

defaultValue(ALREADY_EXISTING_ID)

Upvotes: 2

Related Questions