-- section 表用 image_id 关联 memoir_images,不再存 JSON -- 执行顺序:1) 本文件 2) 回填后执行 DROP 语句(或由脚本完成) -- 执行方式: psql -U -d -f api/migrations/add_section_image_id_fk.sql -- 1. 添加外键列(可空,无默认) ALTER TABLE chapter_sections ADD COLUMN IF NOT EXISTS image_id VARCHAR REFERENCES memoir_images(id) ON DELETE SET NULL; -- 2. 回填:已有 memoir_images 且 section_id 指向本行的,把其 id 写入本行 image_id UPDATE chapter_sections cs SET image_id = sub.id FROM ( SELECT id, section_id FROM memoir_images WHERE section_id IS NOT NULL ) sub WHERE sub.section_id = cs.id AND cs.image_id IS NULL; -- 3. 删除旧的 JSON 列 ALTER TABLE chapter_sections DROP COLUMN IF EXISTS image;