NestJS Prisma ORM - 在获取数据记录时使用"选择"与"包含"?



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

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

当获取'ADMIN'用户记录时,我很难选择使用哪个查询。

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

提前感谢!

代码如下:

使用包括:


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

使用选择:

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

在Select字段和关系查询的文档中有解释,include和Select有不同的用法:

默认情况下,当查询返回记录[..]),结果包括默认选择集:

在Prisma模式中定义的所有标量字段[..]和没有的关系

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

(1)选择:

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

const getUser: object | null = await prisma.user.findUnique({
where: {
id: 22,
},
select: {
email: true,
name: true,
},
})
// Result
{
name: "Alice",
email: "alice@prisma.io",
}

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

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

(2)包括:

允许您返回部分或所有关系字段(如前所述,默认情况下不返回):

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 within Include:

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

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