【问题标题】:How to migrate one-to-one relationship to one-to-many relationship in Realm Swift如何在 Realm Swift 中将一对一关系迁移到一对多关系
【发布时间】:2020-07-23 06:54:44
【问题描述】:

目前,我有两个自定义模型类。我之前在他们之间建立了一对一的关系。但是现在由于新的需求变化,我需要将关系转换为一对多。

例如,这就是我之前构建模型类的方式

class Location: Object {
  @objc dynamic private var id: String = NSUUID().uuidString
  @objc dynamic var typeString: String = 

}

class Job :Object {
@objc dynamic var id: String = NSUUID().uuidString
let location: Location?
}

新结构

class Job :Object {
@objc dynamic var id: String = NSUUID().uuidString
let locations = RealmSwift.List<Location>()
}

所以基本上我想在 Job 类中保存多个位置对象。这种新结构对我来说很好用。但现在我想将旧数据迁移到这个新设置中。我尝试使用以下代码实现此目的,但没有成功。

migration.deleteData(forType: Location.className)
migration.enumerate(ofType:Job.className) { oldObject, newObject in
    let location = migration.create(Location, value: oldObject!["location"]!)
    (newObject!["locations"] as! List<MigrationObject>).append(location)
}

【问题讨论】:

    标签: ios realm swift5


    【解决方案1】:

    简而言之,您有一对一的关系,现在您想将其转换为一对多的关系(通过列表),使用现有位置作为列表中的第一个对象。

    一个 getcha 是您不能有两个具有相同主键的对象,因此在迁移过程中,必须删除旧位置并将替换为具有相同属性(和主键)的新位置,然后将其添加到 Job 的 locations List 属性中。

    代码如下:

    let config = Realm.Configuration( schemaVersion: vers, migrationBlock: { migration, oldSchemaVersion in
         if (oldSchemaVersion < vers) {
            migration.deleteData(forType: Location.className()) //delete all locations
            migration.enumerateObjects(ofType: Job.className()) { oldItem, newItem in
               let existingLoc = oldItem!["location"]
               let updatedLoc = migration.create(Location.className(), value: existingLoc)
               let locList = newItem!["locations"] as! List<MigrationObject>
               locList.append(updatedLoc)
            }
         }
     })
    

    【讨论】:

    • 感谢您的回答。但是当我运行您的代码时出现以下错误。 “List”(又名“List”)类型的值没有成员“append”
    • @user1469015 你安装了什么版本的Realm?另外,看看List 的 RealmSwift API - 你可以看到.append 显然是 List 对象的函数。
    • 我的领域版本 RxRealm (1.0.0) 和。 RealmSwift (~> 3.14)。
    • 这是为我工作的代码。并且迁移工作正常。现在 AppStore 中的应用程序 migration.deleteData(forType: Location.className()) //删除所有位置 migration.enumerateObjects(ofType: Job.className()) { oldItem, newItem in let existingLoc = oldItem!["location"] let updatedLoc = migration.create(Location.className(), value: existingLoc) let locList = newItem?.dynamicList["locations"] locList.append(updatedLoc)
    • 但是我开始收到来自 crashlytics 的周期性崩溃消息,就像这样。 “主键属性 'Location.id' 在迁移后具有重复值。” UserInfo={NSLocalizedDescription=主键属性“Location.id”在迁移后具有重复值
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    相关资源
    最近更新 更多