SwiftData已有One-To-Many关系添加反向关联迁移报错求助
SwiftData 迁移报错 "The current model reference and the next model reference cannot be equal." 解决指南
报错原因
这个错误的核心是:添加反向关联属于模型关系的结构性变更,若你将其与新增字段操作放在同一版本迁移中,SwiftData 可能无法正确计算新旧模型版本的差异,误判两个版本的模型结构一致,从而抛出该异常。即使拆分版本,若模型关系的定义存在疏漏(比如反向关联修饰不完整),也会触发同样问题。
解决方法
1. 拆分迁移版本,单独处理反向关联
不要在同一个版本里同时做「添加反向关联」和「新增字段」操作,分两次迁移完成:
- 先创建
SchemaV1_0_1,仅处理反向关联:- 在
EntityA的subs关联中添加inverse: \SubEntityC.entityA - 在
SubEntityC中新增entityA属性,并标记为反向关联:@Relationship(inverse: \EntityA.subs) var entityA: EntityA?
- 在
- 完成上述版本迁移后,再创建
SchemaV1_1_0,仅新增newProp字段。
2. 手动指定迁移计划,禁用自动迁移依赖
明确定义迁移路径,让 SwiftData 清晰识别版本变化:
// 定义迁移计划 struct MyMigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [SchemaV1_0_0.self, SchemaV1_0_1.self, SchemaV1_1_0.self] } static var stages: [MigrationStage] { [.lightweight(from: SchemaV1_0_0.self, to: SchemaV1_0_1.self), .lightweight(from: SchemaV1_0_1.self, to: SchemaV1_1_0.self)] } } // 初始化容器时指定计划 let schema = Schema([EntityA.self, SubEntityC.self], version: SchemaV1_1_0.self) let container = try ModelContainer(for: schema, migrationPlan: MyMigrationPlan.self)
3. 校验模型关联修饰的正确性
确保新旧版本的模型关联定义无疏漏:
SchemaV1_0_0中EntityA的subs关联不能有inverse参数SchemaV1_1_0(或中间版本SchemaV1_0_1)中,SubEntityC的entityA必须通过@Relationship(inverse: \EntityA.subs)明确标记反向关联
4. 清理缓存与测试数据
旧的模型缓存可能干扰版本识别:
- 删除模拟器中的 App 数据
- 清空 Xcode 的 DerivedData 目录,重新编译项目
5. 验证模型版本哈希差异
打印模型版本的哈希值,确认新旧版本哈希不同(SwiftData 通过哈希识别版本变化):
print("SchemaV1_0_0 hash: \(SchemaV1_0_0.hashValue)") print("SchemaV1_1_0 hash: \(SchemaV1_1_0.hashValue)")
内容的提问来源于stack exchange,提问作者nico_p2000
相关产品推荐
相关产品推荐

