In SwiftData does it matter which model specify the @Relationship?
@Model
class School {
var name: String
@Relationship(deleteRule: .cascade, inverse: \Student.school)
var students: [Student]
}
@Model
class Student {
var name: String
var school: School
}
@Model
class School {
var name: String
var students: [Student]
}
@Model
class Student {
var name: String
@Relationship(deleteRule: .cascade, inverse: \School.students)
var school: School
}
If I delete a School I want all students of that school to also be deleted. Is the logic same for both options?
Yes it definitely matters where you define the delete rule because it always works from the type where you define it.
So for option 1 all Student objects related to a School object will be deleted when you delete the School object
For the second option the School object that is related to the Student object will be deleted when you delete the Student object but any other Student related to the School object will not be deleted.
But there is a problem here: The School property is not an optional for Student so it should not be possible to delete the School in this case, I don't know if the compiler will catch this or if it leads to a runtime crash.
Update: I have confirmed in a test app that the second option will lead to a crash with the error
Cannot remove iOSSwiftDataTest.School from relationship Relationship - name: school, options: [], valueType: School, destination: School, inverseName: students, inverseKeypath: Optional(\School.students) on iOSSwiftDataTest.Student because an appropriate default value is not configured.
And if the School property is optional on the other hand then all other Student objects related to the School will have that property set to nil