如何为对象之间的一对一关系建模?
例如,我有 user_infoA、user_infoB 和 user_profile 的模型。
user_profile
有
- user_id (PK)
- 姓名
- 年龄
user_infoA
有
- info_a_id (PK)
- 用户个人资料
user_infoB
有
- info_b_id (PK)
- 用户个人资料
user_profile
(P) 与user_infoA
(A) 和user_infoB
(B) 都有关系。当A被删除时,P是否也被删除?只有删除相关的 A 和 B 时,P 才会被删除吗?
我如何使用 realm swift 对其进行建模?
多对一关系需要可选属性,这让我可以强制展开可选属性。 :(
[编辑]
class RealmMyProfile: Object {
@objc dynamic var id: Int64 = 0
@objc dynamic var profile = RealmUserProfile()
}
class RealmUserProfile: Object {
@objc dynamic var userId: Int64 = 0
@objc dynamic var name: String = ""
override static func primaryKey() -> String? {
return "userId"
}
}
异常“RealmMyProfile.profile
属性必须标记为可选。”发生了。它应该是可选的。
最佳答案
Realm 中的一对一关系(链接)不能强制链接始终存在。所以它们总是必须标记为可选,因为没有办法阻止 nil 被存储为文件格式的链接。
因此,我们要求在 Swift 中定义的 Realm 模型明确地将一对一关系标记为可选。
class RealmMyProfile: Object {
@objc dynamic var id: Int64 = 0
@objc dynamic var profile:RealmUserProfile?
}
class RealmUserProfile: Object {
@objc dynamic var userId: Int64 = 0
@objc dynamic var name: String = ""
override static func primaryKey() -> String? {
return "userId"
}
}
您可以执行此解决方案,这可能会避免您使用解包值
Realm 问题 2814
dynamic var profile_:RealmUserProfile? = nil
var profile: RealmUserProfile {
get {
return profile_ ?? RealmUserProfile()
}
set {
profile_ = newValue
}
}
关于ios - Realm swift 中的一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49431585/