Skip to content

Cascade Delete with Optional Key? #1726

Answered by groue
bradhowes asked this question in Q&A
Discussion options

You must be logged in to vote

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 the child table:

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)
  }

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@bradhowes
Comment options

Answer selected by bradhowes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants