-
I'm back with another question, this time about cascade deletes for an association that is optional. Does this work? I was experimenting with the Associations playground, and I created Parent and Child records:
I can insert new Parent records with and without a child just fine, and fetching works as one would expect. However, when I delete a parent with a child, I am not seeing the child going away:
The output I get is:
Is this a known limitation? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hello @bradhowes, When people talk about a parent/child relationships in a database, they usually talk about giving multiple children to one parent. You can compare with nodes in a tree: the root node has many children, and their parent is the root node. The canonical database schema for "parents" and "children" is thus to have a migrator.registerMigration("createLibrary") { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.belongsTo("parent", onDelete: .cascade)
}
}
// One parent "has many" children
extension Parent {
static let children = hasMany(Child.self)
}
// One child "belongs to" its parent
extension Child {
static let parent = belongsTo(Parent.self)
} This might sound like useless nitpicking. But we're discussing "parents" and "children", instead of "authors" and "books", or "artists" and "tracks". For clarity's sake, we'd better give their canonical roles to those canonical models.
This now reads "However, when I delete a child, I am not seeing the parent going away". And this is to be expected. When rows are deleted from When rows are deleted from For more information about foreign keys and cascades, please see SQLite documentation. You can also see #1609, which tells how to delete a parent after all its children have been deleted (maybe this is what you are looking after). |
Beta Was this translation helpful? Give feedback.
Hello @bradhowes,
When people talk about a parent/child relationships in a database, they usually talk about giving multiple children to one parent. You can compare with nodes in a tree: the root node has many children, and their parent is the root node.
The canonical database schema for "parents" and "children" is thus to have a
parentId
in thechild
table: