如何属性保存与其他实体具有一对多关系的更新管理对象?

How to property save the updated managed object that has one-to-many relationships with other entities?

如果我的核心数据中有三个实体,它们之间都具有一对多关系:

extension Progress {

    @nonobjc public class func createFetchRequest() -> NSFetchRequest<Progress> {
        return NSFetchRequest<Progress>(entityName: "Progress")
    }

    @NSManaged public var goal: Goal
    @NSManaged public var metric: Set<Metric>

}

extension Metric {

    @nonobjc public class func createFetchRequest() -> NSFetchRequest<Metric> {
        return NSFetchRequest<Metric>(entityName: "Metric")
    }
    
    @NSManaged public var value: NSDecimalNumber
    @NSManaged public var metricToGoal: Goal
    @NSManaged public var progress: Progress

}

extension Goal {

    @nonobjc public class func createFetchRequest() -> NSFetchRequest<Goal> {
        return NSFetchRequest<Goal>(entityName: "Goal")
    }

    @NSManaged public var title: String
    @NSManaged public var progress: Set<Progress>
    @NSManaged public var goalToMetric: Set<Metric>
}

如果获取其中一个实体并更新它:

let metricRequest = Metric.createFetchRequest()
metricRequest.predicate = NSPredicate(format: "value == %@", metric.value)
if let fetchedMetric = try? self.context.fetch(metricRequest) {
   // update Metric
}

我是否还必须获取其余两个实体并将新更新的实体附加到它们?

if let fetchedGoal = try? self.context.fetch(goalRequest) {
   fetchedGoal.goalToMetric.append(updatedMetric)
}

if let fetchedProgress = try? self.context.fetch(goalProgress) {
   fetchedProgress.metric.append(updatedMetric)
}

或者 Core Data 是否足够智能,我只需要为更新的实体保存上下文,它会处理剩下的事情?

Do I have to fetch the rest two entities as well and append the newly updated entity to them?

没有。 您可以阅读有关关系数据库如何工作的更多信息,here

单个 Metric 对象对应于 CoreData-backed 数据库中专用 table 中的单个记录。 如果更新 valueMetric - 不需要更新关系。 在 one-to-many 关系的情况下,数据库中的每个 Metric 记录将仅存储 GoalProgressObjectIDGoalProgress 记录都不会存储与它们相关的指标的任何信息。