SwiftData/PersistentModel.swift:540:Fatal error:Unsupported relationship key path

g2ieeal7  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(115)

我有一对多关系SwiftData模型。但是,当我尝试追加数据时,导致错误SwiftData/PersistentModel.swift:540: Fatal error: Unsupported relationship key path ReferenceWritableKeyPath<Student, School>。我应该如何解决这个问题?

@Model
final class School {
  var name: String
  @Relationship(deleteRule: .cascade, inverse: \Student.school)
  var students: [Student] = []

  init(name: String) {
    self.name = name
  }
}

@Model
final class Student {
  var fullName: String
  var school: School

  init(fullName: String, school: School) {
    self.fullName = fullName
    self.school = school
  }
}

个字符
如果我注解掉self.school.students.append(student)行,它工作正常,但即使我删除学校,属于学校的学生也不会被删除为级联删除。我在苹果论坛https://developer.apple.com/forums/thread/736908上发现了类似的问题

eyh26e7m

eyh26e7m1#

即使您已经为学生分配了学校,也要将该学生附加到学校。

let student = Student(fullName: "Jenny", school: self.school)

字符串
SwiftData将为您处理关系的另一端,因此students.append(student)将在Student init中的self.school = school行自动完成。
因此,只需删除函数中用于添加学生的append()代码即可

private func addStudentToSchool() {
    let student = Student(fullName: "Jenny", school: self.school)
    modelContext.insert(student)
}

相关问题