【问题标题】:Find elements in prisma where they have N+ relations with other elements在 prisma 中查找与其他元素有 N+ 关系的元素
【发布时间】:2022-01-01 01:17:51
【问题描述】:

我有一个 prisma 模式定义如下:

model User {
  id         Int          @id      @default(autoincrement())
  userName   string       @unique
  complaints Complaint[]
}

model Complaint {
  id        Int               @id @default(autoincrement())
  user      User              @relation(fields: [userId], references: [id])
  userId    Int
  priority ComplaintPriority
}

enum ComplaintPriority {
  HIGH
  MEDIUM
  LOW
}

我需要找到所有至少有 N 个投诉且具有HIGHT 优先级(N 变量)的用户,但直到现在我还没有找到方法。理想的情况是使用 SQL 的 having 子句,但我在 groupBy 的用法中找到了有关 having 的文档。

有人知道怎么做吗?

【问题讨论】:

    标签: prisma


    【解决方案1】:

    据我所知,这对于单个 Prisma 查询是不可能的。但是使用两个查询很容易。你会:

    1. complaint 表/模型上使用groupBy 来获取userId 值,其中HIGH 优先投诉的计数超过特定值。
    2. 使用这些userId 值在User 表/模型中执行findMany

    这就是它的样子

    const userIdGroupBy = await prisma.complaint.groupBy({
            by: ["userId"],
            where: {
                priority: "HIGH"
            },
            having: {
                priority: {
                    _count: {
                        gte: _VIOLATION_THRESHOLD_
                    }
                }
            }
        }); 
        
        // convert array of objects to array of id values. 
        let userIdArray = userIdGroupBy.map(item => item.userId)  
    
        let usersWithViolations = await prisma.user.findMany({
            where: {
                id: {
                    in: userIdArray
                }
            }
        })
    
    

    【讨论】:

    • 感谢@Tasin Ishman,它看起来是一个很好的解决方法。你知道表演会有多好/坏吗?特别是对于大量的ids
    • 乐于助人!您可以通过将 query 日志级别传递为 instructed here 来记录 Prisma 生成的 SQL 查询。为这些查询生成的 SQL 对我来说似乎非常有效。这使得 map 操作在 nodejs 中完成。我认为这也不是什么大问题(除非你要处理数百万个我猜的 ID)。
    猜你喜欢
    • 2017-03-16
    • 2020-11-19
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多