how to create a new entry with one-to-many self relation in prisma

Viewed 324

I have a simple model in the schema with one-to-many self relations as shown below, I want to create a parent with it's children at the same time (transaction), how to achieve this?

model X{

  id   Int      @id @default(autoincrement())
  name String

  childXs X[] @relation("childX")

  parentX   X? @relation("childX", fields: [parentXId], references: [id])
  parentXId Int?

}
1 Answers

You could achieve it by doing nested create.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  const createParentAndChild = await prisma.x.create({
    data: {
      name: 'x',
      parentX: {
        create: {
          name: 'parentX',
        },
      },
      childXs: {
        create: {
          name: 'childX',
        },
      },
    },
  });

  console.log('createParentAndChild', createParentAndChild);
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Response:

createParentAndChild { id: 2, name: 'x', parentXId: 1 }
Related