我有一对多关系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
}
}
struct AddStudentToSchoolView: View {
let school: School
@Environment(\.modelContext) private var modelContext
var body: some View {
// code ...
Button("submit". action: { addStudentToSchool() })
}
private func addStudentToSchool() {
let student = Student(fullName: "Jenny", school: self.school)
modelContext.insert(student)
self.school.students.append(student) // <- error SwiftData/PersistentModel.swift:540: Fatal error: Unsupported relationship key path ReferenceWritableKeyPath<Student, School>
}
}
如果我注释掉self.school.students.append(student)
行,它工作得很好,但即使我删除了一所学校,属于该学校的学生也不会像级联删除一样被删除.我在苹果https://developer.apple.com/forums/thread/736908论坛上发现了类似的问题