简体   繁体   中英

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

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?

}

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM