所以我在为 laravel 多态关系编写迁移时遇到了这个问题,Franck 的答案很接近,但错过了更新本地键以匹配新行的部分。
在弗兰克的回答之后,我最初的迁移是
INSERT INTO `block_anchor_blocks` (`anchor_slug`, `label`)
SELECT `title`, `content`
FROM `blocks` where `type` = "anchor";
如果对位于 anchor_block 上的原始块的引用作为 a 属于 this 会很容易,我本可以这样做
INSERT INTO `block_anchor_blocks` (`anchor_slug`, `label`, `block_id`)
SELECT `title`, `content`, `id`
FROM `blocks` where `type` = "anchor";
但这不是多态关系存在于块表中的情况,所以我最终得到了以下代码:
/* Create The New Table */
CREATE TABLE `block_anchor_blocks` (
`id` CHAR(36) PRIMARY KEY,
`anchor_slug` VARCHAR(255),
`label` VARCHAR(255),
`created_at` TIMESTAMP,
`updated_at` TIMESTAMP
);
/* Build the polymorphic fields on the table we're refactoring */
ALTER TABLE `blocks`
ADD `blockable_id` CHAR(36);
ALTER TABLE `blocks`
ADD `blockable_type` VARCHAR(255);
/* Generate the UUID to use when creating an entry in the new table. */
UPDATE `blocks`
SET `blockable_id`=(SELECT UUID()),`blockable_type`="Acme\\Shared\\Entities\\Blocks\\AnchorBlock"
WHERE `type` = "anchor";
/* Finally we Insert using the ID we generated in the last step */
INSERT INTO `block_anchor_blocks` (`anchor_slug`, `label`, `id`, `created_at`, `updated_at`)
SELECT `title`, `content`, `blockable_id`, NOW(), NOW()
FROM `blocks` where `type` = "anchor";
希望这可以帮助其他尝试将大型单个表重构为多个连接表的人。