Even if there are one-many relationship models with the cascade delete rule, SwiftData does not cascade delete items.
For example, there is one school has multiple students like the following models, and even when the school is deleted, the students in the school are not deleted. This happens when a user create a school and students and delete the school immediately.
Are there any workarounds for now?
@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
}
}
I had to remove the inverse to get the cascade delete to work for me. I added it trying to use iCloud. However as iCloud was proving to be a nightmare I abandoned that route. So as I no longer need the requirement for the inverse. I removed it. Then the cascade delete for me worked
Same here, I have to remove the inverse in one-to-many case. Looks like it's a bug in SwiftData since CoreData's behavior confirms the necessity of the inverse.