我有一对多关系 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
即使您已经为学生分配了学校,您仍将学生追加到学校。
SwiftData 将为您处理关系的另一端,因此将在 init中的
students.append(student)
行自动为您完成。self.school = school
Student
因此只需删除添加学生函数中的append()代码即可