Warm tip: This article is reproduced from serverfault.com, please click

One-to-many self-relation in prisma schema

发布于 2020-12-05 22:31:54

I want to create a simple table:

Users
---
id
name
friends

friends field should be an array of other user ids. I'm trying to define a schema for this in schema.prisma:

model User {
  id      String  @id @default(uuid())
  name    String
  friends User[]
}

Saving the file autocompletes the schema to this:

model User {
  id      String  @id @default(uuid())
  name    String
  friends User[]  @relation("UserToUser")
  User    User?   @relation("UserToUser", fields: [userId], references: [id])
  userId  String?
}

I'm not sure how to interpret this. I have read the Prisma docs about one-to-many self relations, but since it states

This relation expresses the following:

  • "a user has zero or one teachers"
  • "a user can have zero or more students"

I doubt it's what I want. How do I get the "a user can have zero or more students" without the "a user has zero or one teachers" part?

Questioner
FistMeNaruto
Viewed
0
Ryan 2020-12-07 18:49:13

Here you need a relation where a User has one or more friends. This would result in a many-to-many self relation as a User can have many friends and also a User can be a friend of other Users.

This can be done as follows:

model User {
  id              String @id @default(uuid())
  name            String
  friends         User[] @relation("friends")
  friendsRelation User[] @relation("friends")
}

the friendsRelation is an extra field and can be ignored as it's only used to store the many-to-many relation.

Creating a User with friends would look something like this:

  await prisma.user.create({
    data: {
      name: 'user 1',
      friends: { create: [{ name: 'user 2' }, { name: 'user 3' }] },
    },
  })

And querying for all users and their friends would be:

await prisma.user.findMany({ include: { friends: true } })