count self relation on Prisma error: table name specified more than once

count self relation on Prisma error: table name specified more than once

我正在尝试计算 Prisma2 中的自我关系(关注者)(使用 PostgreSQL)

型号:

model User {
  id        String  @id @default(cuid())
  following User[]  @relation(name: "UserFollows")
  followers User[]  @relation(name: "UserFollows")
}

查询:

const user = await prisma.user.findUnique({
  where: { id: userId },
  include: {
    _count: {
      select: { followers: true, following: true },
    },
  },
});

(使用 previewFeatures = ["selectRelationCount"])并出现以下错误:

Invalid prisma.user.findUnique() invocation:

Error occurred during query execution: ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState("42712"), message: "table name "User" specified more than once", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("parse_relation.c"), line: Some(423), routine: Some("checkNameSpaceConflicts") }) }) })

有人知道我做错了什么吗?

这是自我关系的一个已知问题,我们希望尽快解决。如果您想跟踪此错误,请遵循此 github issue。请随时添加评论来解释您的使用 case/problem 那边。

同时,您可以使用以下解决方法:

使用嵌套读取查找计数

您可以使用 nested read 来 return followersfollowing 中的所有记录,并找到这些数组的长度以获得计数。这似乎是最直接的方法,只要您可以获取所有 followers/following 记录。

 const user = await prisma.user.findUnique({
        where: {
            id: userId,
        },
        include: {
            followers: true,
            following: true,
        },
    });
    let followerCount = user.followers.length; 
    let followingCount = user.following.length;

使用单独的计数查询查找计数。

或者,您可以使用 count API 查找特定用户的 followersfollowing 计数。

// number of followers for some user "x" = number of times x.id appaers in "following" relation of other users.
    const followerCount = await prisma.user.count({
        where: {
            following: {
                some: {
                    id: userId,
                },
            },
        },
    });

// number of users that user "x" is following = number of times x.id appaers in "followers" relation of other users.
    const followingCount = await prisma.user.count({
        where: {
            followers: {
                some: {
                    id: userId,
                },
            },
        },
    });

更改架构以使用显式多对多表示法

如果您可以稍微调整架构,则可以显式定义多对多关系 table。


model Follows {
  follower    User @relation("follower", fields: [followerId], references: [id])
  followerId  String
  following   User @relation("following", fields: [followingId], references: [id])
  followingId String

  @@id([followerId, followingId])
}

model User {
  id        String  @id @default(cuid())
  followers Follows[] @relation("follower")
  following Follows[] @relation("following")
}

您应该能够 运行 通过这种方式进行计数查询而不会出现问题。