Pytan
Pytan

Reputation: 1674

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

I have one to many relationship SwiftData models. However, when I tried to append data, that causes an error SwiftData/PersistentModel.swift:540: Fatal error: Unsupported relationship key path ReferenceWritableKeyPath<Student, School>. How should I resolve the issue?

@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>
  }
}

If I comment out self.school.students.append(student) line, it works fine, but then even if I delete a school, students that belong to the school are not deleted as cascade delete. I found a similar issue on Apple forum https://developer.apple.com/forums/thread/736908

Upvotes: 6

Views: 2209

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51920

You are appending the student to a school even though you have already assigned a school to the student.

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

SwiftData will handle the other end of the relationship for you so students.append(student) will be done automatically for you at the line self.school = school in the Student init.

So simply remove the append() code in the function for adding a student

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

Upvotes: 6

Related Questions