Post

Replies

Boosts

Views

Activity

Reply to SwiftData does not cascade delete
I found a way to achieve deletion, saving context and make cascade deleteRule working. I'm not sure why it works but it does. This is particular useful for custom ModelContext where autoSave is disabled. First, I make sure that the autoSave feature is disabled. Next, I delete all the models in a single transaction which allows the deletion of child models by cascade. Then I rollback the context. At this step, child models are deleted but not parents. That's why I finally delete models in a new transaction. I know that it's not ideal but It seems to work waiting for a fix. This is my workaround : extension ModelContext { /// Deletes models from ModelContext and saves changes to the persistent storage. /// - Parameter models: the models to delete. /// - Warning: This method is a workaround for deleting models and saving context since explicitly saving context prevents `cascade` delete rule to work. public func deleteAndSave<T: PersistentModel>(_ models: [T]) throws { func deleteModels() { for model in models { delete(model) } } let initialAutosaveState = autosaveEnabled autosaveEnabled = false try transaction { deleteModels() rollback() } try transaction { deleteModels() } autosaveEnabled = initialAutosaveState } }
Feb ’24