explicit prisma many-to-many self relation in typescript

To explicitly define a many-to-many self-relation using Prisma and TypeScript, you can follow these steps:

  1. Define the Prisma model for the entity, let's call it User, in your Prisma schema file (usually named schema.prisma). This model will have a many-to-many relation with itself. Here's an example:
model User {
  id    Int    @id @default(autoincrement())
  name  String
  friends User[] @relation("Friends", references: [id])
}
131 chars
6 lines
  1. Generate the Prisma client by running the npx prisma generate command in your terminal. This will generate the necessary TypeScript typings for your Prisma schema.

  2. In your TypeScript code, import and use the generated PrismaClient instance. You can create, update, or query users using the generated Prisma methods. Here's an example:

index.ts
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function createUsers() {
  const user1 = await prisma.user.create({
    data: {
      name: 'User 1',
      friends: {
        create: [{ name: 'Friend 1' }, { name: 'Friend 2' }],
      },
    },
  })

  const user2 = await prisma.user.create({
    data: {
      name: 'User 2',
      friends: {
        create: [{ name: 'Friend 3' }, { name: 'Friend 4' }],
      },
    },
  })

  // Add user1 and user2 as friends of each other
  await prisma.user.update({
    where: { id: user1.id },
    data: {
      friends: { connect: [{ id: user2.id }] },
    },
  })

  // Query user1 with its friends
  const userWithFriends = await prisma.user.findUnique({
    where: { id: user1.id },
    include: { friends: true },
  })

  console.log(userWithFriends)
}

createUsers()
856 chars
42 lines

In the above example, we create two users, and then connect them as friends. Finally, we query user1 with its friends included.

That's it! You can now use Prisma and TypeScript to define and interact with a many-to-many self-relation using Prisma.

gistlibby LogSnag