Hello, I struggle with seeding my db: I have a se...
# orm-help
j
Hello, I struggle with seeding my db: I have a self referencing entity and if i seed multiple childs to the same parent, only the last child will have a parentId. Everything else works, all the children are in the database... just the parentIds are missing... does anyone have a clue for me? 🙂
Copy code
model Item {
  id          String  @id 
  name        String
  parentId    String?
  parent      Item?   @relation("ItemHierarchy", fields: [parentId], references: [id])
  predecessor Item?   @relation("ItemHierarchy")
}

// seed.js
await prisma.item.upsert({ id: "1", name: "1" }
await prisma.item.upsert({ id: "2", name: "2", { parent: { connect: { id: "1" } } } }
await prisma.item.upsert({ id: "3", name: "3", { parent: { connect: { id: "1" } } } }
...
await prisma.item.upsert({ id: "10", name: "10", { parent: { connect: { id: "1" } } } }
r
@Jan Georg 👋 An item can have multiple children so what you need is a 1-many self relation instead of a 1-1. Your schema should look like this:
Copy code
model Item {
  id       String  @id
  name     String
  children Item[]  @relation("ItemHierarchy")
  parent   Item?   @relation("ItemHierarchy", fields: [parentId], references: [id])
  parentId String?
}
And your query then would be this (the syntax in your question is incorrect):
Copy code
await prisma.item.upsert({
    where: { id: '1' },
    create: { id: '1', name: '1' },
    update: {},
  })

  await prisma.item.upsert({
    where: { id: '2' },
    create: { id: '2', name: '2', parent: { connect: { id: '1' } } },
    update: {},
  })

  await prisma.item.upsert({
    where: { id: '3' },
    create: { id: '3', name: '3', parent: { connect: { id: '1' } } },
    update: {},
  })
You can learn more about data modelling in the docs here.
✅ 1