NestJS Prisma ORM - 在获取数据记录时使用 'select' 还是 'include'?

NestJS Prisma ORM - Using 'select' versus 'include' when fetching data records?

我正在尝试从 NestJS(Node.JS 环境)中的 Postgres 数据库中获取数据记录。

我在 TypeScript 中使用 Prisma 作为我的对象关系映射器 (ORM)。

我在获取 'ADMIN' 用户记录时无法选择要使用的查询。

有人请解释在获取数据记录时使用 'select' 和使用 'include' 之间的区别(我是 Prisma 初学者 - 请保持简单)。

提前致谢!

代码如下所示:

使用包括:


const users = await prisma.user.findMany({
  where: {
    role: 'ADMIN',
  },
  include: {
    posts: true,
  },
})

使用select:

const users = await prisma.user.findMany({
  where: {
    role: 'ADMIN',
  },
  select: {
    posts: true,
  },
})

Select fields and Relation Queries的文档中有说明,include和select有不同的用法:

By default, when a query returns records [..], the result includes the default selection set:

All scalar fields defined in the Prisma schema [..and] None of the relations

要更改此行为,您可以使用:

(1) Select:

允许您 return 字段的有限子集而不是所有字段:

const getUser: object | null = await prisma.user.findUnique({
  where: {
    id: 22,
  },
  select: {
    email: true,
    name: true,
  },
})

// Result
{
  name: "Alice",
  email: "alice@prisma.io",
}

或包含关系和 select 关系字段(嵌套用法):

const users = await prisma.user.findMany({
  select: {
    name: true,
    posts: {
      select: {
        title: true,
      },
    },
  },
})

(2) 包括:

允许您 return 部分或所有关系字段(如前所述,默认情况下未 return 编辑):

const getPosts = await prisma.post.findMany({
  where: {
    title: {
      contains: 'cookies',
    },
  },
  include: {
    author: true, // Return all fields
  },
})

// Result:
;[
  {
    id: 17,
    title: 'How to make cookies',
    published: true,
    authorId: 16,
    comments: null,
    views: 0,
    likes: 0,
    author: {
      id: 16,
      name: null,
      email: 'orla@prisma.io',
      profileViews: 0,
      role: 'USER',
      coinflips: [],
    },
  },
  {
    id: 21,
    title: 'How to make cookies',
    published: true,
    authorId: 19,
    comments: null,
    views: 0,
    likes: 0,
    author: {
      id: 19,
      name: null,
      email: 'emma@prisma.io',
      profileViews: 0,
      role: 'USER',
      coinflips: [],
    },
  },
]

(3) Select 内包括:

最后,您可以在 Include 中使用 Select 来 return 关系字段的子集。

const users = await prisma.user.findMany({
  // Returns all user fields
  include: {
    posts: {
      select: {
        title: true,
      },
    },
  },
})