Prisma - 如何使用 count 作为关系的 where 条件

Fla*_*ryn 5 prisma prisma2

我使用nestjspostgresqlprisma我有两个相关的表,我想创建一个 where 子句,以便在第二个表中的记录计数小于 - 比方说 - 3 时获取记录。更多详细信息;

这是我的架构

model User {
  id                      String            @id
  someOtherFields         String
  outgoingPlayMateRequest PlayMateRequest[] @relation("userId")
  incomingPlayMateRequest PlayMateRequest[] @relation("targetId")
}

model PlayMateRequest {
  id               Int      @id
  requestingUser   User     @relation(name: "userId", fields: [requestingUserId], references: [id], onDelete: Cascade)
  targetUser       User     @relation(name: "targetId", fields: [targetUserId], references: [id], onDelete: Cascade)
  requestingUserId String
  targetUserId     String
  someOtherFields  String
  response         String   //accept-reject-block
}
Run Code Online (Sandbox Code Playgroud)

这是我的带有 where 子句的代码(我通过删除不相关的部分来简化它)

const userId = 'testUser';
return await this.prismaService.user.findMany({
    where: {
      NOT: {
        id: userId //don't fetch user him/herself
      },
      lang: 'EN',
    }
  });
Run Code Online (Sandbox Code Playgroud)

我想用英语在这里添加的条件是;

如果 PlayMateRequest 表中有 3 条带有response = rejectAND 的 记录,则不要选择具有传入PlayMateRequest 关系的用户requestingUser = userId

但我无论如何都找不到count在哪里用作条件。据我所知,我只能计算关系。我怎样才能做到这一点prisma

Tas*_*mam 3

在 Prisma 中没有直接的方法可以实现这样的条件,但您可以使用以下解决方法:

  1. 查询groupBy过滤条件。
  2. 使用 amap创建User.id符合过滤条件的所有用户 ID 的字段数组。
  3. 执行正常查询,但使用过滤后的用户 ID 数组findMany添加额外条件。notIn

整个事情是这样的:

const userId = 'testUser';

// step 1
const dataForFilter = await prisma.playMateRequest.groupBy({
    by: ['targetUserId'],
    where: {
        response: "reject",
        requestingUserId: userId
    },
    having: {
        targetUserId: {
            _count: {
                equals: 3  
            }
        }
    }
})

// step 2
let exclude_users = [userId]
exclude_users = exclude_users.concat(dataForFilter.map(item => item.targetUserId))

let result = await prisma.playMateRequest.user.findMany({
    where: {
        id: {
        notIn: exclude_users
        },
        lang: "en"
    }
    });
Run Code Online (Sandbox Code Playgroud)

我可能误解了您想要实现的查询的确切细节,但我认为这应该为您提供一般的查询结构。根据需要调整groupBy查询以匹配您的确切条件。