我创建了这样的表:
$this->createTable('evenement', [
'id' => $this->integer(),
'description' => $this->string(),
'status' => $this->smallInteger()->defaultValue(10),
'start_datetime' => $this->integer()->notNull(),
'end_datetime' => $this->integer()->notNull()
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
'created_by' => $this->integer(),
'updated_by' => $this->integer(),
], $tableOptions);
$this->createTable('event_participant', [
'event_id' => $this->integer(),
'user_id' => $this->integer(),
'status' => $this->smallInteger()->defaultValue(10),
], $tableOptions);
$this->addPrimaryKey('pk-event_participant', 'event_participant', ['event_id', 'user_id']);
$this->addForeignKey('fk-user_id-event_participant', 'event_participant', 'user_id', 'user', 'id', 'no action');
$this->addForeignKey('fk-event_id-event_participant', 'event_participant', 'event_id', 'evenement', 'id', 'CASCADE');
但我收到此错误,我不知道为什么?我做错了什么?
add foreign key fk-event_id-event_participant: event_participant (event_id) references evenement (id) ...Exception 'yii\db\Exception' with message 'SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint The SQL being executed was: ALTER TABLE `event_participant` ADD CONSTRAINT `fk-event_id-event_participant` FOREIGN KEY (`event_id`) REFERENCES `evenement` (`id`) ON DELETE CASCADE'
答案 0 :(得分:1)
外键只能链接到主键或唯一键。
将PK或UK定义添加到evenement
表
'id' => $this->primaryKey(),
或
'id' => $this->integer()->notNull()->unique(),