Prisma:如何在查询 return 上添加列?

Prisma : how can I add a column on a query return?

假设我有一个带有名称和 ID 的 table User 和一个带有名称和内容的 table Post。两个 table 通过多对多关系链接(一个 post 可以有多个用户/作者,每个用户可以有多个 post)

示例:

model User {
  id            Int      @id @default(autoincrement())
  name          String
  posts         users_to_posts[]
}

model Post {
  id            Int      @id @default(autoincrement())
  name          String
  users         users_to_posts[]
}

model user_to_post {
  user          user? @relation(fields: [user_id], references: [id])
  user_id       Int
  post          signe? @relation(fields: [post_id], references: [id])
  post_id       Int
  @@id([user_id, post_id])
}

我想做的是查询用户 table 并获得写得最多 post 的前 10 个用户。

但是,我不希望仅 return 用户 + post 计数的组合,而是拥有完整的 return 用户、他的 ID 和 posts 他在 returned JSON

中作为一个单独的密钥编写

我试图获得的示例(使用 nextJS):

import { PrismaClient, Prisma } from '@prisma/client'

const prisma = new PrismaClient()


export default async function handler(req, res) {
    const ret = await prisma.user.findMany({
        include: {
            posts: {
                select: {
                    post: true
                }
            }
        }
        // include post count
        // order by post count
        // limit 10
    });
    res.status(200).json(ret)
}

如您所见,我的 table 中没有 'count' 列,必须在查询期间插入

我现在最好的选择是解析获得的 json(ret 变量)并通过打字稿完成所有事情,但这远非理想

您可以使用 orderByuser 记录按 posts 中的 count 排序。此外,您可以使用 take 运算符来限制记录数(类似于 SQL 中的 LIMIT 命令)。最后,要包含 post 的 count,您可以在 include.

中添加它

这是您要查找的查询

await prisma.user.findMany({
    orderBy: {
        posts: {
            _count: "desc",
        },
    },
    take: 10,
    include: {
        _count: {
            select: {
                posts: true,
            },
        },
    },
});

据我从你的问题中了解到,你只想 return post 的 count,而不是 post 记录本身。但是,如果您还想 return post 记录,您也可以将其添加到 include 语句中,就像您目前所做的那样。

进一步阅读文档中使用的运算符: