Reputation: 315
I have two SwiftData models, with a many-to-many relationship between them:
@Model
class Movie {
var name: String?
@Relationship(deleteRule: .nullify, inverse: \Actor.movies)
var actors: [Actor]
init(name: String? = nil, actors: [Actor]) {
self.name = name
self.actors = actors
}
}
@Model
class Actor {
@Attribute(.unique) var name: String?
var movies: [Movie]
init(name: String? = nil, movies: [Movie] = []) {
self.name = name
self.movies = movies
}
}
When I delete a Movie object, I'd like also delete all Actor objects in that movie. But, if that Actor is also in another movie, then I'd like to leave the actor object alone.
What delete rule achieves this? I've tried:
.cascade: Deletes all actors, even if they're starring in another movie. Not what I'd like.
.deny: Not sure what this achieves. The Movie objects disappear, but Actor objects are there and still seem to reference the movies that have been deleted.
.nullify: This is the closest to what I want to achieve, but when the last movie an actor is in is deleted, it still leaves an orphaned Actor object behind.
I think I may have to manually check when a movie is deleted if any of the actors are still being referenced by other movies before deciding to delete or keep them. I wonder is there a better, easier way?
Thank you.
Upvotes: 3
Views: 460