我已经检查过google,但是还没有找到在更改表上的外键时保留数据的方法。
我有两个表格,用户事件和用户运动
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
来自运动表。
现在,当我要将列更改为外键从体育更改为用户体育表格时,我在php artisan migrate
上收到此消息:< / p>
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');
});
}
有人可以指出我正确的方向吗? 谢谢
答案 0 :(得分:0)
必须将一个不是字符串的数组传递给dropForeign方法:$ table-> dropForeign(['event_sport_id']);