我应该如何在 Core Data 中对这些数据建模
How should I model this data in Core Data
我正在尝试对以下数据建模,以便将其存储在 CoreData
中。
因为它使用自定义 类 我不确定如何正确建模。
每个 Account
都有一个 id
和一个 profile
struct Account {
let id: String
let profile: UserProfile
}
每个配置文件都有自己的 id
、一个 name
以及一个 Post
数组
struct UserProfile {
let id: String
let name: String
let posts: [Post]
}
A post 由 id
、一个与个人资料中的 ID 匹配的 authorId
和一个 title
组成
struct Post {
let id: String
let authorId: String // this maps to the UserProfile id field
let title: String
}
一个帐户可以有 1 个配置文件,反之亦然。然而,配置文件可以有 N 个 Posts
.
我假设我需要 3 个实体,帐户、用户配置文件和 Post。
帐户和用户配置文件将具有一对一的关系。
我不确定如何为 UserProfile 和 Post 建模。
UserProfile 是否应该与 Post 具有一对多关系?
是否有可能 Post 与 UserProfile 具有一对一关系,而 UserProfile 与 Post 具有一对多关系?
此外,我假设 CoreData 不支持 Codable
,因此 profile
属性不应作为 Account
上的 Attribute
存在,而是作为Relationships
字段改为?
我的建议:
class Account : NSManagedObject {
@NSManaged var id: String
@NSManaged var profile: UserProfile?
}
class UserProfile : NSManagedObject {
@NSManaged var id: String
@NSManaged var name: String
@NSManaged var account: Account?
@NSManaged var posts: Set<Post>
}
class Post : NSManagedObject {
@NSManaged var id: String
@NSManaged var author: UserProfile?
@NSManaged var title: String
}
profile
in Account
与 UserProfile
是一对一的关系
UserProfile
中的account
与Account
是一对一的反向关系
posts
in UserProfile
是与 Post
的一对多关系
Post
中的 author
与 UserProfile
是一对一的 反向 关系
反向关系比在 Post
中维护 authorId
这样的属性更有效
可以在核心数据中采用 Codable 类(包括关系),但实现起来有点棘手。
我正在尝试对以下数据建模,以便将其存储在 CoreData
中。
因为它使用自定义 类 我不确定如何正确建模。
每个 Account
都有一个 id
和一个 profile
struct Account {
let id: String
let profile: UserProfile
}
每个配置文件都有自己的 id
、一个 name
以及一个 Post
struct UserProfile {
let id: String
let name: String
let posts: [Post]
}
A post 由 id
、一个与个人资料中的 ID 匹配的 authorId
和一个 title
struct Post {
let id: String
let authorId: String // this maps to the UserProfile id field
let title: String
}
一个帐户可以有 1 个配置文件,反之亦然。然而,配置文件可以有 N 个 Posts
.
我假设我需要 3 个实体,帐户、用户配置文件和 Post。
帐户和用户配置文件将具有一对一的关系。
我不确定如何为 UserProfile 和 Post 建模。
UserProfile 是否应该与 Post 具有一对多关系?
是否有可能 Post 与 UserProfile 具有一对一关系,而 UserProfile 与 Post 具有一对多关系?
此外,我假设 CoreData 不支持 Codable
,因此 profile
属性不应作为 Account
上的 Attribute
存在,而是作为Relationships
字段改为?
我的建议:
class Account : NSManagedObject {
@NSManaged var id: String
@NSManaged var profile: UserProfile?
}
class UserProfile : NSManagedObject {
@NSManaged var id: String
@NSManaged var name: String
@NSManaged var account: Account?
@NSManaged var posts: Set<Post>
}
class Post : NSManagedObject {
@NSManaged var id: String
@NSManaged var author: UserProfile?
@NSManaged var title: String
}
profile
inAccount
与UserProfile
是一对一的关系
account
与Account
是一对一的反向关系
posts
inUserProfile
是与Post
的一对多关系
author
与UserProfile
是一对一的 反向 关系
UserProfile
中的Post
中的 反向关系比在 Post
authorId
这样的属性更有效
可以在核心数据中采用 Codable 类(包括关系),但实现起来有点棘手。