【发布时间】:2019-04-26 07:19:11
【问题描述】:
我查了谷歌,但没有找到在更改表上的外键时保留数据的方法。
我有两个表,用户事件和用户运动
Table User Events
+--------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| date | date | YES | | NULL | |
| description | text | YES | | NULL | |
| user_id | int(10) unsigned | YES | MUL | NULL | |
| sport_id | int(10) unsigned | YES | MUL | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| deleted_at | timestamp | YES | MUL | NULL | |
+--------------+------------------+------+-----+---------+----------------+
Table User Sports
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(191) | NO | | NULL | |
| default_sport_id | int(10) unsigned | YES | UNI | NULL | |
| user_id | int(11) | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| deleted_at | timestamp | YES | | NULL | |
+------------------+------------------+------+-----+---------+----------------+
在创建用户运动表之前,在用户事件表中,我有来自运动表的外部 sport_id。
现在,当我想将该列从 Sports 更改为 User Sports 表的外键时,我在php artisan migrate 上收到此消息:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
如果我从 用户事件 中删除 sport_id 列,迁移工作有效,但我不想丢失数据。
这是我的迁移:
public function up()
{
Schema::table('user_events', function (Blueprint $table) {
$table->dropForeign('event_sport_id');
});
Schema::table('user_events', function (Blueprint $table) {
$table->foreign('sport_id')
->references('default_sport_id')
->on('user_sports')
->onDelete('set null');
});
}
有人能指出我正确的方向吗? 谢谢
【问题讨论】:
-
您可以禁用foregin check并运行此迁移
-
外键作为安全网。
标签: laravel laravel-migrations