Skip to main content

Prisma 客户端 API 参考

Prisma 客户端 API 参考文档基于以下架构:

¥The Prisma Client API reference documentation is based on the following schema:

model User {
id Int @id @default(autoincrement())
name String?
email String @unique
profileViews Int @default(0)
role Role @default(USER)
coinflips Boolean[]
posts Post[]
city String
country String
profile ExtendedProfile?
pets Json
}

model ExtendedProfile {
id Int @id @default(autoincrement())
userId Int? @unique
bio String?
User User? @relation(fields: [userId], references: [id])
}

model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(true)
author User @relation(fields: [authorId], references: [id])
authorId Int
comments Json
views Int @default(0)
likes Int @default(0)
}

enum Role {
USER
ADMIN
}

所有示例生成的类型(例如 UserSelectUserWhereUniqueInput)均基于 User 模型。

¥All example generated types (such as UserSelect and UserWhereUniqueInput) are based on the User model.

PrismaClient

本节介绍 PrismaClient 构造函数及其参数。

¥This section describes the PrismaClient constructor and its parameters.

备注

¥Remarks

  • 参数在运行时验证。

    ¥Parameters are validated at runtime.

datasources

以编程方式覆盖 schema.prisma 文件中 datasource 块的属性 - 例如,作为集成测试的一部分。也可以看看:数据源

¥Programmatically overrides properties of the datasource block in the schema.prisma file - for example, as part of an integration test. See also: Data sources

从版本 5.2.0 及更高版本开始,你还可以使用 datasourceUrl 属性以编程方式覆盖数据库连接字符串。

¥From version 5.2.0 and upwards, you can also use the datasourceUrl property to programmatically override the database connection string.

属性

¥Properties

示例属性示例值描述
db{ url: 'file:./dev_qa.db' }数据库 连接网址

备注

¥Remarks

  • 每次添加或重命名数据源时,你都必须重新生成 Prisma 客户端。数据源名称包含在生成的客户端中。

    ¥You must re-generate Prisma Client each time you add or rename a data source. Datasource names are included in the generated client.

  • 如果你在架构中将 datasource 块命名为其他名称,请将 db 替换为 datasource 块的名称。

    ¥If you named your datasource block something else in the schema, replace db with the name of your datasource block.

示例

¥Examples

以编程方式覆盖数据源 url

¥Programmatically override a datasource url

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
datasources: {
db: {
url: 'file:./dev_qa.db',
},
},
});

基于以下 datasource 块:

¥Based on the following datasource block:

datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}

datasourceUrl

以编程方式覆盖 schema.prisma 文件中的 datasource 块。

¥Programmatically overrides the datasource block in the schema.prisma file.

属性

¥Property

选项示例值描述
数据库连接字符串'file:./dev_qa.db'数据库 连接网址

示例

¥Examples

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
datasourceUrl: 'postgresql://johndoe:randompassword@localhost:5432/mydb',
});

log

确定日志记录的类型和级别。也可以看看:记录

¥Determines the type and level of logging. See also: Logging

选项

¥Options

选项示例
日志级别数组[ "info", "query" ]
日志定义数组[ { level: "info", emit: "event" }, { level: "warn", emit: "stdout" }]
日志级别

¥Log levels

名称示例
query记录 Prisma 运行的所有查询。

对于关系数据库,这会记录所有 SQL 查询。示例:
prisma:query SELECT "public"."User"."id", "public"."User"."email" FROM "public"."User" WHERE ("public"."User"."id") IN (SELECT "t0"."id" FROM "public"."User" AS "t0" INNER JOIN "public"."Post" AS "j0" ON ("j0"."authorId") = ("t0"."id") WHERE ("j0"."views" > $1 AND "t0"."id" IS NOT NULL)) OFFSET $2

对于 MongoDB,此日志使用 mongosh 外壳 格式的查询。示例:
prisma:query db.User.deleteMany({ _id: ( $in: [ “6221ce49f756b0721fc00542”, ], }, })
info示例:
prisma:info Started http server on http://127.0.0.1:58471
warn警告。
error错误。
触发格式

¥Emit formats

名称描述
stdout看:stdout
event引发你可以订阅的事件。
事件类型

¥Event types

query 事件类型:

¥The query event type:

index.d.ts
export type QueryEvent = {
timestamp: Date;
query: string; // Query sent to the database
params: string; // Query parameters
duration: number; // Time elapsed (in milliseconds) between client issuing query and database responding - not only time taken to run query
target: string;
};

请注意,对于 MongoDB,paramsduration 字段将是未定义的。

¥Note that for MongoDB, the params and duration fields will be undefined.

所有其他日志级别事件类型:

¥All other log level event types:

index.d.ts
export type LogEvent = {
timestamp: Date;
message: string;
target: string;
};

示例

¥Examples

queryinfo 记录到 stdout

¥Log query and info to stdout

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({ log: ['query', 'info'] });

async function main() {
const countUsers = await prisma.user.count({});
}

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
Show CLI results
query 事件记录到控制台

¥Log a query event to console

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
log: [{ level: 'query', emit: 'event' }],
});

prisma.$on('query', (e) => {
console.log(e);
});

async function main() {
const countUsers = await prisma.user.count({});
}

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
Show CLI results
infowarnerror 事件记录到控制台

¥Log info, warn, and error events to console

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
log: [
{ level: 'warn', emit: 'event' },
{ level: 'info', emit: 'event' },
{ level: 'error', emit: 'event' },
],
});

prisma.$on('warn', (e) => {
console.log(e);
});

prisma.$on('info', (e) => {
console.log(e);
});

prisma.$on('error', (e) => {
console.log(e);
});

async function main() {
const countUsers = await prisma.user.count({});
}

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
Show CLI results

errorFormat

确定 Prisma 客户端返回的错误的级别和格式。

¥Determines the level and formatting of errors returned by Prisma Client.

错误格式

¥Error formats

名称描述
undefined如果未定义,则默认为无色。
pretty启用漂亮的错误格式。
colorless(默认)启用无色错误格式化。
minimal启用最小错误格式化。

示例

¥Examples

没有格式错误

¥No error formatting

const prisma = new PrismaClient({
// Defaults to colorless
});
pretty 格式错误

¥pretty error formatting

const prisma = new PrismaClient({
errorFormat: 'pretty',
});
colorless 格式错误

¥colorless error formatting

const prisma = new PrismaClient({
errorFormat: 'colorless',
});
minimal 格式错误

¥minimal error formatting

const prisma = new PrismaClient({
errorFormat: 'minimal',
});

adapter

定义 驱动适配器 的实例。另请参见 数据库驱动程序

¥Defines an instance of a driver adapter. See also Database drivers .

信息

此功能可从 5.4.0 版及更新版本(位于 driverAdapters 功能标志后面)中获取。

¥This is available from version 5.4.0 and newer behind the driverAdapters feature flag.

示例

¥Example

下面的示例使用 Neon 驱动器适配器

¥The example below uses the Neon driver adapter

import { PrismaNeon } from '@prisma/adapter-neon';
import { PrismaClient } from '@prisma/client';
import dotenv from 'dotenv';

dotenv.config();
const connectionString = `${process.env.DATABASE_URL}`;

const adapter = new PrismaNeon({ connectionString });
const prisma = new PrismaClient({ adapter });

rejectOnNotFound

info

注意:rejectOnNotFound 在 v5.0.0 中被删除。

¥Note: rejectOnNotFound was removed in v5.0.0.

已弃用:rejectOnNotFound 在 v4.0.0 中已弃用。从 v4.0.0 开始,使用查询 findUniqueOrThrowfindFirstOrThrow

¥Deprecated: rejectOnNotFound is deprecated in v4.0.0. From v4.0.0, use the queries findUniqueOrThrow or findFirstOrThrow.

使用 rejectOnNotFound 参数配置 findUnique() 和/或 findFirst,以便在未找到记录时抛出错误。默认情况下,如果未找到记录,这两个操作都会返回 null

¥Use the rejectOnNotFound parameter to configure findUnique() and/or findFirst to throw an error if the record was not found. By default, both operations return null if the record is not found.

备注

¥Remarks

选项

¥Options

选项描述
RejectOnNotFound全局启用 (true / false) 或引发自定义错误。
RejectPerOperation启用每个操作 (true / false) 或针对每个模型的每个操作抛出自定义错误。

示例

¥Examples

全局启用 findUnique()findFirst

¥Enable globally for findUnique() and findFirst

const prisma = new PrismaClient({
rejectOnNotFound: true,
});
全局启用特定操作

¥Enable globally for a specific operation

const prisma = new PrismaClient({
rejectOnNotFound: {
findUnique: true,
},
});
如果未找到记录,则针对每个模型和操作引发自定义错误

¥Throw a custom error per model and operation if record is not found

const prisma = new PrismaClient({
rejectOnNotFound: {
findFirst: {
User: (err) => new Error('User error'),
Post: (err) => new Error('Post error!'),
},
findUnique: {
User: (err) => new Error('User error'),
Post: (err) => new Error('Post error!'),
},
},
});

transactionOptions

info

注意:transactionOptions 是在 v5.10.0 中引入的。

¥Note: transactionOptions was introduced in v5.10.0.

允许在构造函数级别全局设置 事务选项

¥Allows to set transaction options globally on the constructor level.

备注

¥Remarks

  • 可以在每个事务级别上覆盖事务级别。

    ¥The transaction levels can be overridden on a per-transaction level.

选项

¥Options

选项描述
maxWaitPrisma 客户端等待从数据库获取事务的最长时间。默认值为 2 秒。
timeout交互式事务在被取消和回滚之前可以运行的最长时间。默认值为 5 秒。
isolationLevel设置 事务隔离级别。默认情况下,该值设置为数据库中当前配置的值。可用的内容可能因你使用的数据库而异。

示例

¥Example

const prisma = new PrismaClient({
transactionOptions: {
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
maxWait: 5000, // default: 2000
timeout: 10000, // default: 5000
},
});

模型查询

¥Model queries

使用模型查询对模型执行 CRUD 操作。也可以看看:CRUD

¥Use model queries to perform CRUD operations on your models. See also: CRUD

注意:在将任何不受信任的用户数据传递到 Prisma 查询之前,始终对其进行验证和清理是一种最佳做法。如果绕过类型检查,则不这样做可能会导致 SQL 注入或其他注入漏洞。确保用户提供的值不会无意中绕过关键检查。我们强烈建议在应用层执行类型检查和输入验证。有关更多详细信息,请参阅 自定义验证 部分。

¥Note: It's a best practice to always validate and sanitize any untrusted user data before passing it into Prisma queries. Failure to do so can lead to SQL injection or other injection vulnerabilities if the type checks are bypassed. Make sure user-supplied values cannot inadvertently bypass critical checks. We strongly recommend performing type checking and input validation at the application layer. For more details, see Custom Validation section.

findUnique()

findUnique() 查询允许你检索单个数据库记录:

¥findUnique() query lets you retrieve a single database record:

  • 通过 ID

    ¥By ID

  • 通过独特的属性

    ¥By a unique attribute

findUnique() 在版本 2.12.0 中取代了 findOne

¥findUnique() replaced findOne in version 2.12.0.

备注

¥Remarks

  • Prisma 客户端的数据加载器 自动批处理 findUnique() 个查询 具有相同的 selectwhere 参数。

    ¥Prisma Client's dataloader automatically batches findUnique() queries with the same select and where parameters.

  • 如果你希望查询在未找到记录时抛出错误,请考虑使用 findUniqueOrThrow

    ¥If you want the query to throw an error if the record is not found, then consider using findUniqueOrThrow instead.

  • 你不能使用 过滤条件(例如 equalscontainsnot)来过滤 JSON 数据类型的字段。使用过滤条件可能会导致该字段出现 null 响应。

    ¥You cannot use filter conditions (e.g. equals, contains, not) to filter fields of the JSON data type. Using filter conditions will likely result in a null response for that field.

选项

¥Options

名称示例类型 (User)必需的描述
whereUserWhereUniqueInput是的封装模型的所有字段,以便可以选择记录(了解更多)。
在 4.5.0 版本之前,此类型仅封装模型的唯一字段。
selectXOR<UserSelect, null>返回对象上的 指定要包含的属性
includeXOR<UserInclude, null>返回对象上的 指定应立即加载哪些关系
omitXOR<UserOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览
relationLoadStrategy'join''query'默认:join。指定关系查询的 加载策略。仅可与 include(或关系字段上的 select)结合使用。自 预览 5.9.0 起。

返回类型

¥Return type

返回类型示例描述
JavaScript 对象(类型化)User
JavaScript 对象(普通){ title: "Hello world" }使用 selectinclude 确定要返回哪些字段。
nullnull找不到记录

示例

¥Examples

获取 User 记录,id42

¥Get the User record with an id of 42

const result = await prisma.user.findUnique({
where: {
id: 42,
},
});
获取 User 记录,emailalice@prisma.io

¥Get the User record with an email of alice@prisma.io

const result = await prisma.user.findUnique({
where: {
email: 'alice@prisma.io',
},
});
获取 AlicefirstNameSmithlastName@@unique)的 User 记录

¥Get the User record with firstName of Alice and lastName of Smith (@@unique)

Expand for example User model with a @@unique block
model User {
firstName String
lastName String

@@unique(fields: [firstName, lastName], name: "fullname")
}
const result = await prisma.user.findUnique({
where: {
fullname: {
// name property of @@unique attribute - default is firstname_lastname
firstName: 'Alice',
lastName: 'Smith',
},
},
});
获取 AlicefirstNameSmithlastName@@id)的 User 记录

¥Get the User record with firstName of Alice and lastName of Smith (@@id)

Expand for example User model with an @@id block
model User {
firstName String
lastName String

@@id([firstName, lastName])
}
const result = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: 'Alice',
lastName: 'Smith',
},
},
});

findUniqueOrThrow()

findUniqueOrThrow() 以与 findUnique() 相同的方式检索单个记录。但是,如果查询未找到请求的记录,则会抛出 PrismaClientKnownRequestError

¥findUniqueOrThrow() retrieves a single record in the same way as findUnique(). However, if the query does not find the requested record, it throws a PrismaClientKnownRequestError.

请注意 Prisma v6 之前,它会抛出 NotFoundError: No User found error

¥Note that before Prisma v6, it would throw a NotFoundError: No User found error.

以下是其用法的示例:

¥Here’s an example of its usage:

await prisma.user.findUniqueOrThrow({
where: { id: 1 },
});

findUniqueOrThrow()findUnique() 的不同之处如下:

¥findUniqueOrThrow() differs from findUnique() as follows:

  • 它的返回类型是不可为空的。例如,post.findUnique() 可以返回 postnull,但 post.findUniqueOrThrow() 始终返回 post

    ¥Its return type is non-nullable. For example, post.findUnique() can return post or null, but post.findUniqueOrThrow() always returns post.

  • 它与 $transaction API 中的顺序操作不兼容。如果查询抛出 PrismaClientKnownRequestError,则 API 将不会回滚调用数组中的任何操作。作为解决方法,你可以使用 $transaction API 的交互式事务,如下所示:

    ¥It is not compatible with sequential operations in the $transaction API. If the query throws a PrismaClientKnownRequestError, then the API will not roll back any operations in the array of calls. As a workaround, you can use interactive transactions with the $transaction API, as follows:

     $transaction(async (prisma) => {
    await prisma.model.create({ data: { ... });
    await prisma.model.findUniqueOrThrow();
    })

findFirst()

findFirst 返回列表中符合你的条件的第一条记录。

¥findFirst returns the first record in a list that matches your criteria.

备注

¥Remarks

  • 如果你希望查询在未找到记录时抛出错误,请考虑使用 findFirstOrThrow

    ¥If you want the query to throw an error if the record is not found, then consider using findFirstOrThrow instead.

选项

¥Options

名称示例类型 (User)必需的描述
selectXOR<UserSelect, null>返回对象上的 指定要包含的属性
includeXOR<UserInclude, null>返回对象上的 指定应立即加载哪些关系
omitXOR<UserOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览 中。
relationLoadStrategy'join''query'默认:join。指定关系查询的 加载策略。仅可与 include(或关系字段上的 select)结合使用。自 预览 5.9.0 起。
whereUserWhereInput将所有模型字段封装在一个类型中,以便可以按任何属性过滤列表。
orderByXOR<Enumerable<UserOrderByInput>, UserOrderByInput>允许你按任何属性对返回的列表进行排序。

返回类型

¥Return type

返回类型示例描述
JavaScript 对象(类型化)User指定要在返回的对象上包含哪些属性。
JavaScript 对象(普通){ title: "Hello world" }使用 selectinclude 确定要返回哪些字段。
nullnull找不到记录

备注

¥Remarks

  • findFirst 在后台调用 findMany 并接受相同的查询选项。

    ¥findFirst calls findMany behind the scenes and accepts the same query options.

  • 使用 findFirst 查询时传入负 take 值会反转列表的顺序。

    ¥Passing in a negative take value when you use a findFirst query reverses the order of the list.

示例

¥Examples

有关如何过滤结果的示例,请参阅 过滤条件和运算符

¥See Filter conditions and operators for examples of how to filter results.

获取第一个 User 记录,其中 nameAlice

¥Get the first User record where the name is Alice

const user = await prisma.user.findFirst({
where: { name: 'Alice' },
});
获取第一个 Post 记录,其中 titleA test 开头,以 take 反转列表

¥Get the first Post record where the title starts with A test, reverse the list with take

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({});

async function main() {
const a = await prisma.post.create({
data: {
title: 'A test 1',
},
});

const b = await prisma.post.create({
data: {
title: 'A test 2',
},
});

const c = await prisma.post.findFirst({
where: {
title: {
startsWith: 'A test',
},
},
orderBy: {
title: 'asc',
},
take: -1, // Reverse the list
});
}

main();

findFirstOrThrow()

findFirstOrThrow() 以与 findFirst() 相同的方式检索单个数据记录。但是,如果查询未找到记录,则会抛出 PrismaClientKnownRequestError

¥findFirstOrThrow() retrieves a single data record in the same way as findFirst(). However, if the query does not find a record, it throws a PrismaClientKnownRequestError.

请注意 Prisma v6 之前,它会抛出 NotFoundError: No User found error

¥Note that before Prisma v6, it would throw a NotFoundError: No User found error.

findFirstOrThrow()findFirst() 的不同之处如下:

¥findFirstOrThrow() differs from findFirst() as follows:

  • 它的返回类型是不可为空的。例如,post.findFirst() 可以返回 postnull,但 post.findFirstOrThrow 始终返回 post

    ¥Its return type is non-nullable. For example, post.findFirst() can return post or null, but post.findFirstOrThrow always returns post.

  • 它与 $transaction API 中的顺序操作不兼容。如果查询返回 PrismaClientKnownRequestError,则 API 将不会回滚调用数组中的任何操作。作为解决方法,你可以使用 $transaction API 的交互式事务,如下所示:

    ¥It is not compatible with sequential operations in the $transaction API. If the query returns PrismaClientKnownRequestError, then the API will not roll back any operations in the array of calls. As a workaround, you can use interactive transactions with the $transaction API, as follows:

    prisma.$transaction(async (tx) => {
    await tx.model.create({ data: { ... });
    await tx.model.findFirstOrThrow();
    })

findMany()

findMany 返回记录列表。

¥findMany returns a list of records.

选项

¥Options

名称类型必需的描述
selectXOR<PostSelect, null>返回对象上的 指定要包含的属性
includeXOR<PostInclude, null>返回对象上的 指定应立即加载哪些关系
omitXOR<PostOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览
relationLoadStrategy'join''query'默认:join。指定关系查询的 加载策略。仅可与 include(或关系字段上的 select)结合使用。自 预览 5.9.0 起。
whereUserWhereInput将所有模型字段封装在一个类型中,以便可以按任何属性过滤列表。
orderByXOR<Enumerable<PostOrder
ByInput>, PostOrderByInput>
允许你按任何属性对返回的列表进行排序。
cursorUserWhereUniqueInput指定列表的位置(该值通常指定 id 或另一个唯一值)。
takenumber指定列表中应返回多少个对象(从列表的开头(正值)或结尾(负值)或从 cursor 位置(如果提到))
skipnumber指定应跳过列表中返回的对象数量。
distinctEnumerable<UserDistinctFieldEnum>允许你按特定字段过滤掉重复行 - 例如,仅返回不同的 Post 标题。

返回类型

¥Return type

返回类型示例描述
JavaScript 数组对象(类型化)User[]
JavaScript 数组对象(普通)[{ title: "Hello world" }]使用 selectinclude 确定要返回哪些字段。
空数组[]未找到匹配的记录。

示例

¥Examples

有关如何过滤结果的示例,请参阅 过滤条件和运算符

¥See Filter conditions and operators for examples of how to filter results.

获取所有 User 记录,其中 nameAlice

¥Get all User records where the name is Alice

const user = await prisma.user.findMany({
where: { name: 'Alice' },
});

create()

create 创建一条新的数据库记录。

¥create creates a new database record.

选项

¥Options

名称类型必需的描述
dataXOR<UserCreateInput,
UserUncheckedCreateInput>
是的将所有模型字段封装在一个类型中,以便在创建新记录时可以提供它们。它还包括允许你执行(事务性)嵌套插入的关系字段。数据模型中标记为可选或具有默认值的字段是可选的。
selectXOR<UserSelect, null>返回对象上的 指定要包含的属性
includeXOR<UserInclude, null>返回对象上的 指定应立即加载哪些关系
omitXOR<UserOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览
relationLoadStrategy'join''query'默认:join。指定关系查询的 加载策略。仅可与 include(或关系字段上的 select)结合使用。自 预览 5.9.0 起。

返回类型

¥Return type

返回类型示例描述
JavaScript 对象(类型化)User
JavaScript 对象(普通){ name: "Alice Wonderland" }使用 selectinclude 确定要返回哪些字段。

备注

¥Remarks

  • 你还可以执行嵌套 create - 例如,同时添加一条 User 和两条 Post 记录。

    ¥You can also perform a nested create - for example, add a User and two Post records at the same time.

示例

¥Examples

使用唯一必填字段 email 创建一条新记录

¥Create a single new record with the only required field email

const user = await prisma.user.create({
data: { email: 'alice@prisma.io' },
});
创建多个新记录

¥Create multiple new records

在大多数情况下,你可以使用 createMany()createManyAndReturn() 查询进行批量插入。然而,在某些情况下,create() 是插入多条记录的最佳选择.

¥In most cases, you can carry out batch inserts with the createMany() or createManyAndReturn() queries. However, there are scenarios where create() is the best option to insert multiple records.

以下示例产生两个 INSERT 语句:

¥The following example results in two INSERT statements:

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

const prisma = new PrismaClient({ log: ['query'] });

async function main() {
let users: Prisma.UserCreateInput[] = [
{
email: 'ariana@prisma.io',
name: 'Ari',
profileViews: 20,
coinflips: [true, false, false],
role: 'ADMIN',
},
{
email: 'elsa@prisma.io',
name: 'Elsa',
profileViews: 20,
coinflips: [true, false, false],
role: 'ADMIN',
},
];

await Promise.all(
users.map(async (user) => {
await prisma.user.create({
data: user,
});
})
);
}

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
Show CLI results
prisma:query BEGIN
prisma:query INSERT INTO "public"."User" ("name","email","profileViews","role","coinflips") VALUES ($1,$2,$3,$4,$5) RETURNING "public"."User"."id"
prisma:query SELECT "public"."User"."id", "public"."User"."name", "public"."User"."email", "public"."User"."profileViews", "public"."User"."role", "public"."User"."coinflips" FROM "public"."User" WHERE "public"."User"."id" = $1 LIMIT $2 OFFSET $3
prisma:query INSERT INTO "public"."User" ("name","email","profileViews","role","coinflips") VALUES ($1,$2,$3,$4,$5) RETURNING "public"."User"."id"
prisma:query COMMIT
prisma:query SELECT "public"."User"."id", "public"."User"."name", "public"."User"."email", "public"."User"."profileViews", "public"."User"."role", "public"."User"."coinflips" FROM "public"."User" WHERE "public"."User"."id" = $1 LIMIT $2 OFFSET $3
prisma:query COMMIT

update()

update 更新现有数据库记录。

¥update updates an existing database record.

选项

¥Options

名称类型必需的描述
dataXOR<UserUpdateInput
UserUncheckedUpdateInput>
是的封装模型的所有字段,以便在更新现有记录时可以提供它们。数据模型中标记为可选或具有默认值的字段是可选的。
whereUserWhereUniqueInput是的封装模型的所有字段,以便可以选择记录(了解更多)。
在 4.5.0 版本之前,此类型仅封装模型的唯一字段。
selectXOR<UserSelect, null>返回对象上的 指定要包含的属性
includeXOR<UserInclude, null>返回对象上的 指定应立即加载哪些关系
omitXOR<UserOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览 中。
relationLoadStrategy'join''query'默认:join。指定关系查询的 加载策略。仅可与 include(或关系字段上的 select)结合使用。自 预览 5.9.0 起。

返回类型

¥Return type

返回类型示例描述
JavaScript 对象(类型化)User
JavaScript 对象(普通){ name: "Alice Wonderland" }使用 selectinclude 确定要返回哪些字段。
RecordNotFound 异常如果记录不存在,则抛出异常。

备注

¥Remarks

  • 要在更新时执行算术运算(加、减、乘、除),请使用 原子更新 来防止竞争条件。

    ¥To perform arithmetic operations on update (add, subtract, multiply, divide), use atomic updates to prevent race conditions.

  • 你还可以执行嵌套 update - 例如,同时更新用户和该用户的帖子。

    ¥You can also perform a nested update - for example, update a user and that user's posts at the same time.

示例

¥Examples

User 记录的 email1id 更新为 alice@prisma.io

¥Update the email of the User record with id of 1 to alice@prisma.io

const user = await prisma.user.update({
where: { id: 1 },
data: { email: 'alice@prisma.io' },
});

upsert()

info

本节介绍 upsert() 操作的用法。要了解如何在 update() 中使用 嵌套更新插入查询,请参考链接文档。

¥This section covers the usage of the upsert() operation. To learn about using nested upsert queries within update(), reference the linked documentation.

upsert 执行以下操作:

¥upsert does the following:

  • 如果现有数据库记录满足 where 条件,则会更新该记录

    ¥If an existing database record satisfies the where condition, it updates that record

  • 如果没有数据库记录满足 where 条件,则创建一条新的数据库记录

    ¥If no database record satisfies the where condition, it creates a new database record

选项

¥Options

名称类型必需的描述
createXOR<UserCreateInput,
UserUncheckedCreateInput>
是的封装模型的所有字段,以便在创建新记录时可以提供它们。它还包括允许你执行(事务性)嵌套插入的关系字段。数据模型中标记为可选或具有默认值的字段是可选的。
updateXOR<UserUpdateInput,
UserUncheckedUpdateInput>
是的封装模型的所有字段,以便在更新现有记录时可以提供它们。数据模型中标记为可选或具有默认值的字段是可选的。
whereUserWhereUniqueInput是的封装模型的所有字段,以便可以选择记录(了解更多)。
在 4.5.0 版本之前,此类型仅封装模型的唯一字段。
selectXOR<UserSelect, null>返回对象上的 指定要包含的属性
includeXOR<UserInclude, null>返回对象上的 指定应立即加载哪些关系
omitXOR<UserOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览
relationLoadStrategy'join''query'默认:join。指定关系查询的 加载策略。仅可与 include(或关系字段上的 select)结合使用。自 预览 5.9.0 起。

返回类型

¥Return type

返回类型示例描述
JavaScript 对象(类型化)User
JavaScript 对象(普通){ name: "Alice Wonderland" }使用 selectinclude 确定要返回哪些字段。

备注

¥Remarks

  • 要在更新时执行算术运算(加、减、乘、除),请使用 原子更新 来防止竞争条件。

    ¥To perform arithmetic operations on update (add, subtract, multiply, divide), use atomic updates to prevent race conditions.

  • 如果两个或多个更新插入操作同时发生并且记录尚不存在,则可能会发生竞争条件。因此,一个或多个更新插入操作可能会引发唯一键约束错误。你的应用代码可以捕获此错误并重试该操作。了解更多

    ¥If two or more upsert operations happen at the same time and the record doesn't already exist, then a race condition might happen. As a result, one or more of the upsert operations might throw a unique key constraint error. Your application code can catch this error and retry the operation. Learn more.

  • 从版本 4.6.0 开始,Prisma ORM 在可能的情况下将更新插入查询移交给数据库。了解更多

    ¥From version 4.6.0, Prisma ORM hands over upsert queries to the database where possible. Learn more.

示例

¥Examples

更新(如果存在)或创建一条 emailalice@prisma.io 的新 User 记录

¥Update (if exists) or create a new User record with an email of alice@prisma.io

const user = await prisma.user.upsert({
where: { id: 1 },
update: { email: 'alice@prisma.io' },
create: { email: 'alice@prisma.io' },
});

更新插入时出现唯一键约束错误

¥Unique key constraint errors on upserts

问题

¥Problem

如果多个 upsert 操作同时发生并且该记录尚不存在,则一个或多个操作可能会返回 唯一键约束错误

¥If multiple upsert operations happen at the same time and the record doesn't already exist, then one or more of the operations might return a unique key constraint error.

原因

¥Cause

当 Prisma 客户端执行更新插入时,它首先检查该记录是否已存在于数据库中。为了进行此检查,Prisma 客户端使用 upsert 操作中的 where 子句执行读取操作。这有两种可能的结果,如下:

¥When Prisma Client does an upsert, it first checks whether that record already exists in the database. To make this check, Prisma Client performs a read operation with the where clause from the upsert operation. This has two possible outcomes, as follows:

  • 如果该记录不存在,Prisma 客户端将创建该记录。

    ¥If the record does not exist, then Prisma Client creates that record.

  • 如果记录存在,Prisma 客户端会更新它。

    ¥If the record exists, then Prisma Client updates it.

当你的应用尝试执行两个或多个并发更新插入操作时,可能会发生竞争条件,其中两个或多个操作找不到记录,因此尝试创建该记录。在这种情况下,其中一个操作成功创建新记录,但其他操作失败并返回唯一键约束错误。

¥When your application tries to perform two or more concurrent upsert operations, then a race condition might happen where two or more operations do not find the record and therefore try to create that record. In this situation, one of the operations successfully creates the new record but the other operations fail and return a unique key constraint error.

解决方案

¥Solution

处理应用代码中的 P2002 错误。发生这种情况时,请重试 upsert 操作以更新该行。

¥Handle the P2002 error in your application code. When it occurs, retry the upsert operation to update the row.

数据库更新插入

¥Database upserts

在可能的情况下,Prisma 客户端会将 upsert 查询移交给数据库。这称为数据库更新插入。

¥Where possible, Prisma Client hands over an upsert query to the database. This is called a database upsert.

数据库更新插入具有以下优点:

¥Database upserts have the following advantages:

当满足 具体标准 时,Prisma 客户端会自动使用数据库更新插入。当不满足这些条件时,Prisma 客户端将处理 upsert

¥Prisma Client uses a database upsert automatically when specific criteria are met. When these criteria are not met, Prisma Client handles the upsert.

要使用数据库更新插入,Prisma 客户端将 SQL 构造 INSERT ... ON CONFLICT SET .. WHERE 发送到数据库。

¥To use a database upsert, Prisma Client sends the SQL construction INSERT ... ON CONFLICT SET .. WHERE to the database.

数据库更新插入先决条件

¥Database upsert prerequisites

如果你的堆栈满足以下条件,Prisma 客户端可以使用数据库更新插入:

¥Prisma Client can use database upserts if your stack meets the following criteria:

  • 你使用 Prisma ORM 版本 4.6.0 或更高版本

    ¥You use Prisma ORM version 4.6.0 or later

  • 你的应用使用 CockroachDB、PostgreSQL 或 SQLite 数据源

    ¥Your application uses a CockroachDB, PostgreSQL, or SQLite data source

数据库更新插入查询条件

¥Database upsert query criteria

当查询满足以下条件时,Prisma 客户端会对 upsert 查询使用数据库更新插入:

¥Prisma Client uses a database upsert for an upsert query when the query meets the following criteria:

  • upsertcreateupdate options 中没有嵌套查询

    ¥There are no nested queries in the upsert's create and update options

  • 该查询不包含使用 嵌套读取 的选择

    ¥The query does not include a selection that uses a nested read

  • 查询仅修改一个模型

    ¥The query modifies only one model

  • upsertwhere 选项中只有一个唯一字段

    ¥There is only one unique field in the upsert's where option

  • where 选项中的唯一字段和 create 选项中的唯一字段具有相同的值

    ¥The unique field in the where option and the unique field in the create option have the same value

如果你的查询不满足这些条件,Prisma 客户端将自行处理更新插入。

¥If your query does not meet these criteria, then Prisma Client handles the upsert itself.

数据库更新插入示例

¥Database upsert examples

以下示例使用此架构:

¥The following examples use this schema:

model User {
id Int @id
profileViews Int
userName String @unique
email String

@@unique([id, profileViews])
}

以下 upsert 查询满足所有条件,因此 Prisma 客户端使用数据库更新插入。

¥The following upsert query meets all of the criteria, so Prisma Client uses a database upsert.

prisma.user.upsert({
where: {
userName: 'Alice',
},
create: {
id: 1,
profileViews: 1,
userName: 'Alice',
email: 'alice@prisma.io',
},
update: {
email: 'updated@example.com',
},
});

在这种情况下,Prisma 使用以下 SQL 查询:

¥In this situation, Prisma uses the following SQL query:

INSERT INTO "public"."User" ("id","profileViews","userName","email") VALUES ($1,$2,$3,$4)
ON CONFLICT ("userName") DO UPDATE
SET "email" = $5 WHERE ("public"."User"."userName" = $6 AND 1=1) RETURNING "public"."User"."id", "public"."User"."profileViews", "public"."User"."userName", "public"."User"."email"

以下查询在 where 子句中有多个唯一值,因此 Prisma 客户端不使用数据库更新插入:

¥The following query has multiple unique values in the where clause, so Prisma Client does not use a database upsert:

prisma.User.upsert({
where: {
userName: 'Alice',
profileViews: 1,
id: 1,
},
create: {
id: 1,
profileViews: 1,
userName: 'Alice',
email: 'alice@prisma.io',
},
update: {
email: 'updated@example.com',
},
});

在以下查询中,wherecreate 选项中 userName 的值不同,因此 Prisma Client 不使用数据库 upsert。

¥In the following query, the values for userName in the where and create options are different, so Prisma Client does not use a database upsert.

prisma.User.upsert({
where: {
userName: 'Alice',
},
create: {
id: 1,
profileViews: 1,
userName: 'AliceS',
email: 'alice@prisma.io',
},
update: {
email: 'updated@example.com',
},
});

在以下查询中,对 poststitle 字段的选择是嵌套读取,因此 Prisma Client 不使用数据库 upsert。

¥In the following query, the selection on the title field in posts is a nested read, so Prisma Client does not use a database upsert.

prisma.user.upsert({
select: {
email: true,
id: true,
posts: {
select: {
title: true,
},
},
},
where: {
userName: 'Alice',
},

create: {
id: 1,
profileViews: 1,
userName: 'Alice',
email: 'alice@prisma.io',
},
update: {
email: 'updated@example.com',
},
});

delete()

delete 删除现有数据库记录。你可以删除一条记录:

¥delete deletes an existing database record. You can delete a record:

  • 通过 ID

    ¥By ID

  • 通过独特的属性

    ¥By a unique attribute

要删除符合特定条件的记录,请将 deleteMany 与过滤器结合使用。

¥To delete records that match a certain criteria, use deleteMany with a filter.

选项

¥Options

名称类型必需的描述
whereUserWhereUniqueInput是的封装模型的所有字段,以便可以选择记录(了解更多)。
在 4.5.0 版本之前,此类型仅封装模型的唯一字段。
selectXOR<UserSelect, null>返回对象上的 指定要包含的属性
includeXOR<UserInclude, null>返回对象上的 指定应立即加载哪些关系
omitXOR<UserOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览
relationLoadStrategy'join''query'默认:join。指定关系查询的 加载策略。仅可与 include(或关系字段上的 select)结合使用。自 预览 5.9.0 起。

返回类型

¥Return type

返回类型示例描述
JavaScript 对象(类型化)User已删除的 User 记录。
JavaScript 对象(普通){ name: "Alice Wonderland" }已删除的 User 记录中的数据。使用 selectinclude 确定要返回哪些字段。
RecordNotFound 异常如果记录不存在则抛出异常。

备注

¥Remarks

  • 要根据某些条件删除多条记录(例如,所有具有 prisma.io 电子邮件地址的 User 记录,请使用 deleteMany

    ¥To delete multiple records based on some criteria (for example, all User records with a prisma.io email address, use deleteMany)

示例

¥Examples

删除 id1User 记录

¥Delete the User record with an id of 1

const user = await prisma.user.delete({
where: { id: 1 },
});
删除 email 等于 else@prisma.ioUser 记录

¥Delete the User record where email equals else@prisma.io

以下查询删除特定用户记录并使用 select 返回已删除用户的 nameemail

¥The following query deletes a specific user record and uses select to return the name and email of the deleted user:

const deleteUser = await prisma.user.delete({
where: {
email: 'elsa@prisma.io',
},
select: {
email: true,
name: true,
},
});
Show CLI results
{ "email": "elsa@prisma.io", "name": "Elsa" }

createMany()

createMany 在一个事务中创建多条记录。

¥createMany creates multiple records in a transaction.

选项

¥Options

名称类型必需的描述
dataEnumerable<UserCreateManyInput>是的将所有模型字段封装在一个类型中,以便在创建新记录时可以提供它们。数据模型中标记为可选或具有默认值的字段是可选的。
skipDuplicates?boolean不要插入具有唯一字段或已存在的 ID 字段的记录。仅受支持 ON CONFLICT DO NOTHING 的数据库支持。这不包括 MongoDB 和 SQLServer

返回类型

¥Return type

返回类型示例描述
BatchPayload{ count: 3 }创建的记录数的计数。

备注

¥Remarks

  • 从 Prisma ORM 版本 5.12.0 开始,SQLite 现在支持 createMany()

    ¥As of Prisma ORM version 5.12.0, createMany() is now supported by SQLite.

  • MongoDB、SQLServer 或 SQLite 不支持 skipDuplicates 选项。

    ¥The skipDuplicates option is not supported by MongoDB, SQLServer, or SQLite.

  • 你无法通过在顶层 createMany() 查询内使用嵌套 createcreateManyconnectconnectOrCreate 查询来创建或连接关系。有关 workaround,请参阅此处。

    ¥You cannot create or connect relations by using nested create, createMany, connect, connectOrCreate queries inside a top-level createMany() query. See here for a workaround.

  • 你可以在 update()create() 查询中使用嵌套的 createMany 查询 - 例如,同时添加一条 User 和两条 Post 记录,并嵌套 createMany

    ¥You can use a nested createMany query inside an update() or create() query - for example, add a User and two Post records with a nested createMany at the same time.

示例

¥Examples

创建几个新用户

¥Create several new users

const users = await prisma.user.createMany({
data: [
{ name: 'Sonali', email: 'sonali@prisma.io' },
{ name: 'Alex', email: 'alex@prisma.io' },
],
});

createManyAndReturn()

createManyAndReturn 创建多个记录并返回结果对象。

¥createManyAndReturn creates multiple records and returns the resulting objects.

信息

此功能在 Prisma ORM 版本 5.14.0 及更高版本中可用于 PostgreSQL、CockroachDB 和 SQLite。

¥This feature is available in Prisma ORM version 5.14.0 and later for PostgreSQL, CockroachDB and SQLite.

选项

¥Options

名称类型必需的描述
dataEnumerable<UserCreateManyInput>是的将所有模型字段封装在一个类型中,以便在创建新记录时可以提供它们。数据模型中标记为可选或具有默认值的字段是可选的。
selectXOR<UserSelect, null>指定要包含的属性 在返回的对象上。
omitXOR<UserOmit, null>指定在返回的对象上排除哪些属性。自 5.13.0 起在 预览 中。与 select 互斥。
includeXOR<UserInclude, null>指定应立即加载哪些关系 在返回的对象上。
skipDuplicates?boolean不要插入具有唯一字段或已存在的 ID 字段的记录。仅受支持 ON CONFLICT DO NOTHING 的数据库支持。这不包括 MongoDB 和 SQLServer

备注

¥Remarks

  • SQLite 不支持 skipDuplicates 选项。

    ¥The skipDuplicates option is not supported by SQLite.

  • 请注意,createManyAndReturn 返回的元素顺序无法保证。

    ¥Note that the order of elements returned by createManyAndReturn is not guaranteed.

  • 你无法通过在顶层 createManyAndReturn() 查询内使用嵌套 createcreateManyconnectconnectOrCreate 查询来创建或连接关系。有关 workaround,请参阅此处。

    ¥You cannot create or connect relations by using nested create, createMany, connect, connectOrCreate queries inside a top-level createManyAndReturn() query. See here for a workaround.

  • 当通过 include 包含关系时,每个关系都会生成一个单独的查询。

    ¥When relations are included via include, a separate query is generated per relation.

  • 不支持 relationLoadStrategy: join

    ¥relationLoadStrategy: join is not supported.

返回类型

¥Return type

返回类型示例描述
JavaScript 数组对象(类型化)User[]
JavaScript 数组对象(普通)[{ name: "Sonali" }]使用 selectomitinclude 确定要返回哪些字段。

示例

¥Examples

创建并返回多个新用户

¥Create and return several new users

const users = await prisma.user.createManyAndReturn({
data: [
{ name: 'Sonali', email: 'sonali@prisma.io' },
{ name: 'Alex', email: 'alex@prisma.io' },
],
})
Show CLI results
[
{ "id": 0, "name": "Sonali", "email": "sonali@prisma.io", "profileViews": 0 },
{ "id": 1, "name": "Alex", "email": "alex@prisma.io", "profileViews": 0 }
]

updateMany()

updateMany 批量更新一批已有的数据库记录,并返回更新的记录条数。

¥updateMany updates a batch of existing database records in bulk and returns the number of updated records.

选项

¥Options

名称类型必需的描述
dataXOR<UserUpdateManyMutationInput,
UserUncheckedUpdateManyInput>
是的封装模型的所有字段,以便在更新现有记录时可以提供它们。数据模型中标记为可选或具有默认值的字段在 data 上是可选的。
whereUserWhereInput封装模型的所有字段,以便可以按任何属性过滤列表。如果你不过滤列表,所有记录都将被更新。
limitnumber限制要更新的记录数。

返回类型

¥Return type

返回类型示例描述
BatchPayload{ count: 4 }更新记录的计数。
export type BatchPayload = {
count: number;
};

示例

¥Examples

nameAlice 的所有 User 记录更新为 ALICE

¥Update all User records where the name is Alice to ALICE

const updatedUserCount = await prisma.user.updateMany({
where: { name: 'Alice' },
data: { name: 'ALICE' },
});
更新所有 User 记录,其中 email 包含 prisma.io 并且至少一个相关 Post 的点赞次数超过 10 个

¥Update all User records where the email contains prisma.io and at least one related Post has more than 10 likes

const updatedUserCount = await prisma.user.updateMany({
where: {
email: {
contains: 'prisma.io',
},
posts: {
some: {
likes: {
gt: 10,
},
},
},
},
data: {
role: 'USER',
},
});
更新 email 包含 prisma.ioUser 记录,但限制更新 5 条记录。

¥Update User records where the email contains prisma.io, but limit to 5 records updated.

const updatedUserCount = await prisma.user.updateMany({
where: {
email: {
contains: 'prisma.io',
},
},
data: {
role: 'USER',
},
limit: 5,
});

updateManyAndReturn()

信息

此功能在 Prisma ORM 版本 6.2.0 及更高版本中可用于 PostgreSQL、CockroachDB 和 SQLite。

¥This feature is available in Prisma ORM version 6.2.0 and later for PostgreSQL, CockroachDB and SQLite.

updateManyAndReturn 更新多个记录并返回结果对象。

¥updateManyAndReturn updates multiple records and returns the resulting objects.

选项

¥Options

名称类型必需的描述
dataXOR<UserUpdateManyMutationInput,
UserUncheckedUpdateManyInput>
是的封装模型的所有字段,以便在更新现有记录时可以提供它们。数据模型中标记为可选或具有默认值的字段在 data 上是可选的。
whereUserWhereInput封装模型的所有字段,以便可以按任何属性过滤列表。如果你不过滤列表,所有记录都将被更新。

返回类型

¥Return type

返回类型示例描述
JavaScript 数组对象(类型化)User[]
JavaScript 数组对象(普通)[{ name: "Sonali" }]使用 selectomitinclude 确定要返回哪些字段。

示例

¥Examples

更新并返回多个用户

¥Update and return multiple users

const users = await prisma.user.updateManyAndReturn({
where: {
email: {
contains: 'prisma.io',
}
},
data: {
role: 'ADMIN'
},
})
Show CLI results
[
{ "id": 0, "name": "Sonali", "email": "sonali@prisma.io", "role": "ADMIN", "profileViews": 0 },
{ "id": 1, "name": "Alex", "email": "alex@prisma.io", "role": "ADMIN", "profileViews": 0 }
]

deleteMany()

deleteMany 删除事务中的多条记录。

¥deleteMany deletes multiple records in a transaction.

选项

¥Options

名称类型必需的描述
whereUserWhereInput封装模型的所有字段,以便可以按任何字段过滤列表。
limitInt限制删除的记录数。

返回类型

¥Return type

返回类型示例描述
BatchPayload{ count: 4 }已删除记录的计数。
export type BatchPayload = {
count: number;
};

示例

¥Examples

删除所有 User 记录

¥Delete all User records

const deletedUserCount = await prisma.user.deleteMany({});
删除 nameAlice 的所有 User 记录

¥Delete all User records where the name is Alice

const deletedUserCount = await prisma.user.deleteMany({
where: { name: 'Alice' },
});
删除所有 User 记录,其中 email 包含 prisma.io,但限制删除 5 条记录。

¥Delete all User records where the email contains prisma.io, but limit to 5 records deleted.

const deletedUserCount = await prisma.user.deleteMany({
where: {
email: {
contains: 'prisma.io',
},
},
limit: 5,
});

有关如何过滤要删除的记录的示例,请参阅 过滤条件和运算符

¥See Filter conditions and operators for examples of how to filter the records to delete.

count()

选项

¥Options

名称类型必需的描述
whereUserWhereInput将所有模型字段封装在一个类型中,以便可以按任何属性过滤列表。
orderByXOR<Enumerable<PostOrder
ByInput>, PostOrderByInput>
允许你按任何属性对返回的列表进行排序。
cursorUserWhereUniqueInput指定列表的位置(该值通常指定 id 或另一个唯一值)。
takenumber指定列表中应返回多少个对象(从列表的开头(正值)或结尾(负值)或从 cursor 位置(如果提到))
skipnumber指定应跳过列表中返回的对象数量。

返回类型

¥Return type

返回类型示例描述
number29记录数。
UserCountAggregateOutputType{ _all: 27, name: 10 }如果使用 select,则返回。

示例

¥Examples

统计所有 User 条记录

¥Count all User records

const result = await prisma.user.count();
计算所有 User 记录中至少有一条已发布的 Post

¥Count all User records with at least one published Post

const result = await prisma.user.count({
where: {
post: {
some: {
published: true,
},
},
},
});
使用 select 执行三个单独的计数

¥Use select to perform three separate counts

以下查询返回:

¥The following query returns:

  • 所有记录的计数 (_all)

    ¥A count of all records (_all)

  • 具有非 null name 字段的所有记录的计数

    ¥A count of all records with non-null name fields

  • 具有非 null city 字段的所有记录的计数

    ¥A count of all records with non-null city fields

const c = await prisma.user.count({
select: {
_all: true,
city: true,
name: true,
},
});

aggregate()

也可以看看:聚合、分组和总结

¥See also: Aggregation, grouping, and summarizing

选项

¥Options

名称类型必需的描述
whereUserWhereInput将所有模型字段封装在一个类型中,以便可以按任何属性过滤列表。
orderByXOR<Enumerable<UserOrderByInput>,
UserOrderByInput>
允许你按任何属性对返回的列表进行排序。
cursorUserWhereUniqueInput指定列表的位置(该值通常指定 id 或另一个唯一值)。
takenumber指定列表中应返回多少个对象(从列表的开头(正值)或结尾(负值)或从 cursor 位置(如果提到))
skipnumber指定应跳过列表中返回的对象数量。
_counttrue返回匹配记录或非 null 字段的计数。
_avgUserAvgAggregateInputType返回指定字段的所有值的平均值。
_sumUserSumAggregateInputType返回指定字段的所有值的总和。
_minUserMinAggregateInputType返回指定字段的最小可用值。
_maxUserMaxAggregateInputType返回指定字段的最大可用值。

示例

¥Examples

返回所有 User 条记录中 profileViews 条的 _min_max_count

¥Return _min, _max, and _count of profileViews of all User records

const minMaxAge = await prisma.user.aggregate({
_count: {
_all: true,
},
_max: {
profileViews: true,
},
_min: {
profileViews: true,
},
});
Show CLI results
返回所有 User 记录的所有 profileViews 中的 _sum

¥Return _sum of all profileViews for all User records

const setValue = await prisma.user.aggregate({
_sum: {
profileViews: true,
},
});
Show CLI results

groupBy()

也可以看看:聚合、分组和总结

¥See also: Aggregation, grouping, and summarizing

选项

¥Options

名称类型必需的描述
whereUserWhereInput将所有模型字段封装在一个类型中,以便可以按任何属性过滤列表。
orderByXOR<Enumerable<UserOrderByInput>,
UserOrderByInput>
允许你按 by 中也存在的任何属性对返回的列表进行排序。
byArray<UserScalarFieldEnum> | string指定用于对记录进行分组的字段或字段组合。
havingUserScalarWhereWithAggregatesInput允许你按聚合值过滤组 - 例如,仅返回平均年龄小于 50 岁的群体。
takenumber指定列表中应返回多少个对象(从列表的开头(正值)或结尾(负值)或从 cursor 位置(如果提到))
skipnumber指定应跳过列表中返回的对象数量。
_counttrue | UserCountAggregateInputType返回匹配记录或非 null 字段的计数。
_avgUserAvgAggregateInputType返回指定字段的所有值的平均值。
_sumUserSumAggregateInputType返回指定字段的所有值的总和。
_minUserMinAggregateInputType返回指定字段的最小可用值。
_maxUserMaxAggregateInputType返回指定字段的最大可用值。

示例

¥Examples

country/city 进行分组,其中 profileViews 的平均值大于 200,并返回每组 profileViews_sum

¥Group by country/city where the average profileViews is greater than 200, and return the _sum of profileViews for each group

该查询还返回每个组中 _all 条记录的计数,以及每个组中具有非 null city 字段值的所有记录。

¥The query also returns a count of _all records in each group, and all records with non-null city field values in each group.

const groupUsers = await prisma.user.groupBy({
by: ['country', 'city'],
_count: {
_all: true,
city: true,
},
_sum: {
profileViews: true,
},
orderBy: {
country: 'desc',
},
having: {
profileViews: {
_avg: {
gt: 200,
},
},
},
});
Show CLI results
[
{
country: 'Denmark',
city: 'Copenhagen',
_sum: { profileViews: 490 },
_count: {
_all: 70,
city: 8,
},
},
{
country: 'Sweden',
city: 'Stockholm',
_sum: { profileViews: 500 },
_count: {
_all: 50,
city: 3,
},
},
];

findRaw()

看:使用原始 SQL (findRaw())

¥See: Using Raw SQL (findRaw()).

aggregateRaw()

看:使用原始 SQL (aggregateRaw())

¥See: Using Raw SQL (aggregateRaw()).

型号查询选项

¥Model query options

select

select 定义 Prisma 客户端返回的对象中包含哪些字段。看:选择字段并包含关系 .

¥select defines which fields are included in the object that Prisma Client returns. See: Select fields and include relations .

备注

¥Remarks

示例

¥Examples

选择单个 User 记录的 nameprofileViews 字段

¥Select the name and profileViews fields of a single User record

const result = await prisma.user.findUnique({
where: { id: 1 },
select: {
name: true,
profileViews: true,
},
});
Show CLI results
选择多条 User 记录的 emailrole 字段

¥Select the email and role fields of a multiple User records

const result = await prisma.user.findMany({
select: {
email: true,
role: true,
},
});
Show CLI results
选择 _count 个关系

¥Select a _count of relations

const usersWithCount = await prisma.user.findMany({
select: {
_count: {
select: { posts: true },
},
},
});
Show CLI results
选择相关 Post 记录的 'id' 和 'title' 字段

¥Select the 'id' and 'title' fields of related Post records

const result = await prisma.user.findMany({
select: {
id: true,
name: true,
posts: {
select: {
id: true,
title: true,
},
},
},
});
Show CLI results
include 里面 select

¥include inside select

const result = await prisma.user.findMany({
select: {
id: true,
name: true,
posts: {
include: {
author: true,
},
},
},
});
Show CLI results

select 生成的类型

¥Generated types for select

以下示例演示了如何将 validatorselect 一起使用:

¥The following example demonstrates how to use the validator with select:

const selectNameEmailNotPosts = Prisma.validator<Prisma.UserSelect>()({
name: true,
email: true,
posts: false,
});

include

include 定义 Prisma 客户端返回的结果中包含哪些关系。看:选择字段并包含关系 .

¥include defines which relations are included in the result that Prisma Client returns. See: Select fields and include relations .

备注

¥Remarks

示例

¥Examples

加载 User 条记录时包含 postsprofile 关系

¥Include the posts and profile relation when loading User records

const users = await prisma.user.findMany({
include: {
posts: true, // Returns all fields for all posts
profile: true, // Returns all Profile fields
},
});
使用两个 Post 记录创建新的 User 记录时,在返回的对象上包含 posts 关系

¥Include the posts relation on the returned objects when creating a new User record with two Post records

const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [{ title: 'This is my first post' }, { title: 'Here comes a second post' }],
},
},
include: { posts: true }, // Returns all fields for all posts
});

include 生成的类型

¥Generated types for include

以下示例演示了如何将 validatorinclude 一起使用:

¥The following example demonstrates how to use the validator with include:

const includePosts = Prisma.validator<Prisma.UserInclude>()({
posts: true,
});
包括 _count 个关系

¥Include a _count of relations

const usersWithCount = await prisma.user.findMany({
include: {
_count: {
select: { posts: true },
},
},
});
Show CLI results

omit

omit 定义 Prisma Client 返回的对象中排除哪些字段。

¥omit defines which fields are excluded in the object that Prisma Client returns.

备注

¥Remarks

  • 你不能组合 omitselect,因为它们的用途相反

    ¥You cannot combine omit and select since they serve opposite purposes

  • omit 已随 Prisma ORM 6.2.0 发布到通用可用性。它通过 Prisma ORM 版本 5.13.06.1.0 中的 omitApi 预览功能 提供。

    ¥omit was released into General Availability with Prisma ORM 6.2.0. It was available via the omitApi Preview feature in Prisma ORM versions 5.13.0 through 6.1.0.

示例

¥Examples

从所有 User 记录中省略 password 字段

¥Omit the password field from all User records

const result = await prisma.user.findMany({
omit: {
password: true,
},
});
Show CLI results
从所有 Userposts 关系中省略 title 字段

¥Omit the title fields from all User's posts relation

const results = await prisma.user.findMany({
omit: {
password: true,
},
include: {
posts: {
omit: {
title: true,
},
},
},
});
Show CLI results

omit 生成的类型

¥Generated types for omit

以下示例演示了如何将 validatoromit 一起使用:

¥The following example demonstrates how to use the validator with omit:

const omitPassword = Prisma.validator<Prisma.UserOmit>()({
password: true,
});

relationLoadStrategy(预览)

¥relationLoadStrategy (Preview)

relationLoadStrategy 指定如何从数据库加载关系。它有两个可能的值:

¥relationLoadStrategy specifies how a relation should be loaded from the database. It has two possible values:

  • join(默认):使用数据库级 LATERAL JOIN (PostgreSQL) 或相关子查询 (MySQL),并通过对数据库的单个查询获取所有数据。

    ¥join (default): Uses a database-level LATERAL JOIN (PostgreSQL) or correlated subqueries (MySQL) and fetches all data with a single query to the database.

  • query:向数据库发送多个查询(每个表一个)并在应用级别连接它们。

    ¥query: Sends multiple queries to the database (one per table) and joins them on the application level.

注意:一旦 relationLoadStrategy预览 移动到 一般可用性join 将普遍成为所有关系查询的默认值。

¥Note: Once relationLoadStrategy moves from Preview into General Availability, join will universally become the default for all relation queries.

你可以了解有关加入策略 此处 的更多信息。

¥You can learn more about join strategies here.

由于 relationLoadStrategy 选项当前处于预览状态,因此你需要通过 Prisma 架构文件中的 relationJoins 预览功能标志启用它:

¥Because the relationLoadStrategy option is currently in Preview, you need to enable it via the relationJoins preview feature flag in your Prisma schema file:

generator client {
provider = "prisma-client-js"
previewFeatures = ["relationJoins"]
}

添加此标志后,你需要再次运行 prisma generate 以重新生成 Prisma Client。relationJoins 功能目前在 PostgreSQL、CockroachDB 和 MySQL 上可用。

¥After adding this flag, you need to run prisma generate again to re-generate Prisma Client. The relationJoins feature is currently available on PostgreSQL, CockroachDB and MySQL.

备注

¥Remarks

  • 大多数情况下,默认的 join 策略会更有效。如果你想节省数据库服务器上的资源或者你的分析表明应用级联接性能更高,请使用 query

    ¥In most situations, the default join strategy will be more effective. Use query if you want to save resources on your database server or if you profiling shows that the application-level join is more performant.

  • 你只能在查询的顶层指定 relationLoadStrategy。顶层选择将影响所有嵌套子查询。

    ¥You can only specify the relationLoadStrategy on the top-level in your query. The top-level choice will affect all nested sub-queries.

示例

¥Examples

使用 include 时通过数据库级 JOIN 加载 posts 关系

¥Load the posts relation via a database-level JOIN when using include

const users = await prisma.user.findMany({
relationLoadStrategy: 'join',
include: {
posts: true,
},
});
使用 select 时通过数据库级 JOIN 加载 posts 关系

¥Load the posts relation via a database-level JOIN when using select

const users = await prisma.user.findMany({
relationLoadStrategy: 'join',
select: {
posts: true,
},
});

where

where 定义一个或多个 filters,可用于过滤记录属性(如用户的电子邮件地址)或相关记录属性(如用户最近的 10 个帖子标题)。

¥where defines one or more filters, and can be used to filter on record properties (like a user's email address) or related record properties (like a user's top 10 most recent post titles).

示例

¥Examples

const results = await prisma.user.findMany({
where: {
email: {
endsWith: 'prisma.io',
},
},
});

where 生成的类型

¥Generated types for where

以下示例演示了如何将 validatorwhere 结合使用:

¥The following examples demonstrate how to use the validator with where:

  • UserWhereInput

    // UserWhereInput
    const whereNameIs = Prisma.validator<Prisma.UserWhereInput>()({
    name: 'Rich',
    });

    // It can be combined with conditional operators too
    const whereNameIs = Prisma.validator<Prisma.UserWhereInput>()({
    name: 'Rich',
    AND: [
    {
    email: {
    contains: 'rich@boop.com',
    },
    },
    ],
    });
  • UserWhereUniqueInput 这种类型的工作原理是公开模型上的任何唯一字段。指定为 @id 的字段被认为是唯一的,指定为 @unique 的字段也是如此。

    ¥UserWhereUniqueInput This type works by exposing any unique fields on the model. A field assigned @id is considered unique, as is one assigned @unique.

    从版本 4.5.0 开始,此类型公开模型上的所有字段。这意味着当你根据唯一字段筛选单个记录时,你可以同时检查其他非唯一字段和唯一字段。了解更多

    ¥From version 4.5.0, this type exposes all fields on the model. This means that when you filter for a single record based on a unique field, you can check additional non-unique and unique fields at the same time. Learn more.

    // UserWhereUniqueInput
    const whereEmailIsUnique = Prisma.validator<Prisma.UserWhereUniqueInput>()({
    email: 'rich@boop.com',
    })
  • PostScalarWhereInput

    const whereScalarTitleIs = Prisma.validator<Prisma.PostScalarWhereInput>()({
    title: 'boop',
    });
  • PostUpdateWithWhereUniqueWithoutAuthorInput - 此类型接受唯一的 where 字段(@id 或另一个分配的 @unique)并更新 Post 模型上除 Author 之外的任何字段。AuthorPost 模型上的标量场。

    ¥PostUpdateWithWhereUniqueWithoutAuthorInput - This type accepts a unique where field (an @id or another assigned @unique) and updates any field on the Post model except the Author. The Author is the scalar field on the Post model.

    const updatePostByIdWithoutAuthor =
    Prisma.validator<Prisma.PostUpdateWithWhereUniqueWithoutAuthorInput>()({
    where: {
    id: 1,
    },
    data: {
    content: 'This is some updated content',
    published: true,
    title: 'This is a new title',
    },
    });
  • PostUpsertWithWhereUniqueWithoutAuthorInput - 此类型将更新 id 匹配的 Post 记录标题字段,如果不存在,则会创建它。

    ¥PostUpsertWithWhereUniqueWithoutAuthorInput - This type will update the Post records title field where the id matches, if it doesn't exist it will create it instead.

    const updatePostTitleOrCreateIfNotExist =
    Prisma.validator<Prisma.PostUpsertWithWhereUniqueWithoutAuthorInput>()({
    where: {
    id: 1,
    },
    update: {
    title: 'This is a new title',
    },
    create: {
    id: 1,
    title: 'If the title doesnt exist, then create one with this text',
    },
    });
  • PostUpdateManyWithWhereWithoutAuthorInput - 此类型将更新所有已发布设置为 false 的 Post 记录。

    ¥PostUpdateManyWithWhereWithoutAuthorInput - This type will update all Post records where published is set to false.

    const publishAllPosts = Prisma.validator<Prisma.PostUpdateManyWithWhereWithoutAuthorInput>()({
    where: {
    published: {
    equals: false,
    },
    },
    data: {
    published: true,
    },
    });

orderBy

对记录列表进行排序。也可以看看:排序

¥Sorts a list of records. See also: Sorting

备注

¥Remarks

sort 参数的输入

¥Inputs for sort argument

名称描述
asc升序排序 (A → Z)
desc降序排序 (Z → A)

nulls 参数的输入

¥Inputs for nulls argument

注意:

¥Note:

  • 该参数是可选的。

    ¥This argument is optional.

  • 它仅用于可选的 scalar 字段。如果你尝试按必填字段或 relation 字段上的空值进行排序,Prisma 客户端会抛出 P2009 错误

    ¥It is for use on optional scalar fields only. If you try to sort by nulls on a required or relation field, Prisma Client throws a P2009 error.

  • 它在 4.1.0 及更高版本中作为预览功能提供。有关如何启用该功能的详细信息,请参阅 首先或最后以空值排序

    ¥It is available in version 4.1.0 and later, as a preview feature. See sort with nulls first or last for details of how to enable the feature.

名称描述
first首先按 null 值排序。
last最后按 null 值排序。

示例

¥Examples

email 字段对 User 进行排序

¥Sort User by email field

以下示例返回按 email 升序排序的所有 User 记录:

¥The following example returns all User records sorted by email ascending:

const users = await prisma.user.findMany({
orderBy: {
email: 'asc',
},
});

以下示例返回按 email 降序排序的所有 User 记录:

¥The following example returns all User records sorted by email descending:

const users = await prisma.user.findMany({
orderBy: {
email: 'desc',
},
});

按相关 User 记录的 namePost 进行排序

¥Sort Post by the related User record's name

以下查询按用户名对帖子进行排序:

¥The following query orders posts by user name:

const posts = await prisma.post.findMany({
orderBy: {
author: {
name: 'asc',
},
},
});

按相关 User 记录的 namePost 进行排序,首先是 null 记录

¥Sort Post by the related User record's name, with null records first

以下查询按用户名对帖子进行排序,首先是 null 记录:

¥The following query orders posts by user name, with null records first:

const posts = await prisma.post.findMany({
orderBy: {
author: {
name: { sort: 'asc', nulls: 'first' },
},
},
});

按标题的相关性对 Post 进行排序

¥Sort Post by relevance of the title

信息

对于 PostgreSQL,此功能仍处于预览阶段。启用 fullTextSearchPostgres 功能标记 才能使用它。

¥For PostgreSQL, this feature is still in Preview. Enable the fullTextSearchPostgres feature flag in order to use it.

以下查询根据搜索词 'database' 与标题的相关性对帖子进行排序:

¥The following query orders posts by relevance of the search term 'database' to the title:

const posts = await prisma.post.findMany({
orderBy: {
_relevance: {
fields: ['title'],
search: 'database',
sort: 'asc'
},
})

posts 计数对 User 进行排序

¥Sort User by the posts count

以下查询按帖子数对用户进行排序:

¥The following query orders users by post count:

const getActiveusers = await prisma.user.findMany({
orderBy: {
posts: {
count: 'desc',
},
},
});
按多个字段对 User 进行排序 - emailrole

¥Sort User by multiple fields - email and role

以下示例按两个字段对用户进行排序 - 首先是 email,然后是 role

¥The following example sorts users by two fields - first email, then role:

const users = await prisma.user.findMany({
select: {
email: true,
role: true,
},
orderBy: [
{
email: 'desc',
},
{
role: 'desc',
},
],
});
Show CLI results

参数排序的顺序很重要 - 以下查询按 role 排序,然后按 email 排序。不是结果的差异:

¥The order of sorting parameters matters - the following query sorts by role, then email. Not the difference in the results:

const users = await prisma.user.findMany({
select: {
email: true,
role: true,
},
orderBy: [
{
role: 'desc',
},
{
email: 'desc',
},
],
});
Show CLI results
email 排序 User,选择 nameemail

¥Sort User by email, select name and email

以下示例返回所有 User 记录的所有 nameemail 字段,按 email 排序:

¥The following example returns all the name and email fields of all User records, sorted by email:

const users3 = await prisma.user.findMany({
orderBy: {
email: 'asc',
},
select: {
name: true,
email: true,
},
});
Show CLI results
email 排序 User 记录并按 title 排序嵌套的 Post 记录

¥Sort User records by email and sort nested Post records by title

下面的例子:

¥The following example:

  • 返回按 email 排序的所有 User 记录

    ¥Returns all User records sorted by email

  • 对于每条 User 记录,返回按 title 排序的所有嵌套 Post 记录的 title 字段

    ¥For each User record, returns the title field of all nested Post records sorted by title

const usersWithPosts = await prisma.user.findMany({
orderBy: {
email: 'asc',
},
include: {
posts: {
select: {
title: true,
},
orderBy: {
title: 'asc',
},
},
},
});
Show CLI results
对一个用户的 Post 条记录的嵌套列表进行排序

¥Sort one user's nested list of Post records

以下示例按 ID 检索单个 User 记录,以及按 title 排序的嵌套 Post 记录列表:

¥The following example retrieves a single User record by ID, as well as a list of nested Post records sorted by title:

const userWithPosts = await prisma.user.findUnique({
where: {
id: 1,
},
include: {
posts: {
orderBy: {
title: 'desc',
},
select: {
title: true,
published: true,
},
},
},
});
Show CLI results
enum 排序

¥Sort by enum

以下命令按 roleenum)对所有 User 记录进行排序:

¥The following sorts all User records by role (an enum):

const sort = await prisma.user.findMany({
orderBy: {
role: 'desc',
},
select: {
email: true,
role: true,
},
});
Show CLI results

orderBy 生成的类型

¥Generated types for orderBy

以下示例演示了如何将 validatororderBy 结合使用:

¥The following examples demonstrate how to use the validator with orderBy:

  • UserOrderByInput
    const orderEmailsByDescending = Prisma.validator<Prisma.UserOrderByInput>()({
    email: 'desc',
    });

distinct

findManyfindFirst 中的记录列表进行数据去重。也可以看看:聚合、分组和总结

¥Deduplicate a list of records from findMany or findFirst. See also: Aggregation, grouping, and summarizing

示例

¥Examples

在单个字段上选择不同的

¥Select distinct on a single field

以下示例返回所有不同的 city 字段,并仅选择 citycountry 字段:

¥The following example returns all distinct city fields, and selects only the city and country fields:

const distinctCities = await prisma.user.findMany({
select: {
city: true,
country: true,
},
distinct: ['city'],
});
Show CLI results
[
{ city: 'Paris', country: 'France' },
{ city: 'Lyon', country: 'France' },
];
在多个字段上选择不同的

¥Select distinct on multiple fields

以下示例返回所有不同的 citycountry 字段组合,并仅选择 citycountry 字段:

¥The following example returns all distinct city and country field combinations, and selects only the city and country fields:

const distinctCitiesAndCountries = await prisma.user.findMany({
select: {
city: true,
country: true,
},
distinct: ['city', 'country'],
});
Show CLI results
[
{ city: 'Paris', country: 'France' },
{ city: 'Paris', country: 'Denmark' },
{ city: 'Lyon', country: 'France' },
];

请注意,除了 "法国巴黎" 之外,现在还有 "丹麦巴黎":

¥Note that there is now a "Paris, Denmark" in addition to "Paris, France":

与过滤器结合选择不同的

¥Select distinct in combination with a filter

以下示例返回用户电子邮件包含 "prisma.io" 的所有不同 citycountry 字段组合,并仅选择 citycountry 字段:

¥The following example returns all distinct city and country field combinations where the user's email contains "prisma.io", and selects only the city and country fields:

const distinctCitiesAndCountries = await prisma.user.findMany({
where: {
email: {
contains: 'prisma.io',
},
},
select: {
city: true,
country: true,
},
distinct: ['city', 'country'],
});
Show CLI results

nativeDistinct

在 Prisma 模式中启用 nativeDistinct 会将 distinct 操作推送到数据库层(如果支持)。这可以显著提高性能。但请注意:

¥Enabling nativeDistinct in your Prisma schema pushes the distinct operation to the database layer (where supported). This can significantly improve performance. However, note that:

  • 某些数据库可能不完全支持某些字段组合的 DISTINCT 功能。

    ¥Some databases may not fully support DISTINCT on certain field combinations.

  • 不同提供商的行为可能有所不同。

    ¥Behavior can differ among providers.

启用 nativeDistinct

¥To enable nativeDistinct:

generator client {
provider = "prisma-client-js"
previewFeatures = ["nativeDistinct"]
}

详细信息请参见 预览功能

¥See Preview Features for more details.

嵌套查询

¥Nested queries

create

嵌套 create 查询将新的相关记录或记录集添加到父记录中。看:与关系合作

¥A nested create query adds a new related record or set of records to a parent record. See: Working with relations

备注

¥Remarks

  • 当你 create() (prisma.user.create(...)) 一条新父记录或 update() (prisma.user.update(...)) 一条现有父记录时,create 可用作嵌套查询。

    ¥create is available as a nested query when you create() (prisma.user.create(...)) a new parent record or update() (prisma.user.update(...)) an existing parent record.

  • 你可以使用嵌套的 create 或嵌套的 createMany 创建多个相关记录。如果你需要 skipDuplicates 查询选项,则应使用 createMany

    ¥You can use a nested create or a nested createMany to create multiple related records. If you require the skipDuplicates query option you should use createMany.

示例

¥Examples

使用新的 Profile 记录创建新的 User 记录

¥Create a new User record with a new Profile record

const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
profile: {
create: { bio: 'Hello World' },
},
},
});
使用新的 User 记录创建新的 Profile 记录

¥Create a new Profile record with a new User record

const user = await prisma.profile.create({
data: {
bio: 'Hello World',
user: {
create: { email: 'alice@prisma.io' },
},
},
})
使用新的 Post 记录创建新的 User 记录

¥Create a new User record with a new Post record

const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
},
});
使用两条新的 Post 记录创建一条新的 User 记录

¥Create a new User record with two new Post records

因为它是一对多关系,所以你还可以在通过将数组传递给 create 一次:

¥Because it's a one-to-many relation, you can also create multiple Post records at once by passing an array to create:

const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{
title: 'This is my first post',
},
{
title: 'Here comes a second post',
},
],
},
},
});

注意:你还可以使用嵌套的 createMany 来实现相同的结果。

¥Note: You can also use a nested createMany to achieve the same result.

通过创建新的 Profile 记录来更新现有的 User 记录

¥Update an existing User record by creating a new Profile record

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
profile: {
create: { bio: 'Hello World' },
},
},
});
通过创建新的 Post 记录来更新现有的 User 记录

¥Update an existing User record by creating a new Post record

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
create: { title: 'Hello World' },
},
},
})

createMany

嵌套 createMany 查询将一组新记录添加到父记录中。看:与关系合作

¥A nested createMany query adds a new set of records to a parent record. See: Working with relations

备注

¥Remarks

  • 当你 create() (prisma.user.create(...)) 一条新父记录或 update() (prisma.user.update(...)) 一条现有父记录时,createMany 可用作嵌套查询。

    ¥createMany is available as a nested query when you create() (prisma.user.create(...)) a new parent record or update() (prisma.user.update(...)) an existing parent record.

    • 在一对多关系的上下文中可用 - 例如,你可以 prisma.user.create(...) 一个用户并使用嵌套 createMany 创建多个帖子(帖子有一个用户)。

      ¥Available in the context of a one-to-many relation — for example, you can prisma.user.create(...) a user and use a nested createMany to create multiple posts (posts have one user).

    • 在多对多关系的上下文中不可用 - 例如,你不能 prisma.post.create(...) 帖子并使用嵌套 createMany 来创建类别(许多帖子有许多类别)。

      ¥Not available in the context of a many-to-many relation — for example, you cannot prisma.post.create(...) a post and use a nested createMany to create categories (many posts have many categories).

  • 你不能嵌套额外的 createcreateMany

    ¥You cannot nest an additional create or createMany.

  • 允许直接设置外键 - 例如,在帖子上设置 categoryId

    ¥Allows setting foreign keys directly — for example, setting the categoryId on a post.

  • 从 Prisma ORM 版本 5.12.0 开始,SQLite 支持嵌套 createMany

    ¥As of Prisma ORM version 5.12.0, nested createMany is supported by SQLite.

  • 你可以使用嵌套 create 或嵌套 createMany 创建多个相关记录 - 如果你不需要 skipDuplicates 查询选项,你可能应该使用 create

    ¥You can use a nested create or a nested createMany to create multiple related records - if you do not need the skipDuplicates query option, you should probably use create.

选项

¥Options {#nested-createmany-options}

名称类型必需的描述
dataEnumerable<UserCreateManyInput>是的将所有模型字段封装在一个类型中,以便在创建新记录时可以提供它们。数据模型中标记为可选或具有默认值的字段是可选的。
skipDuplicates?boolean不要插入具有唯一字段或已存在的 ID 字段的记录。仅受支持 ON CONFLICT DO NOTHING 的数据库支持。这不包括 MongoDB 和 SQLServer

示例

¥Examples

更新一条 User 和多个新的相关 Post 记录

¥Update a User and multiple new related Post records

const user = await prisma.user.update({
where: {
id: 9,
},
data: {
name: 'Elliott',
posts: {
createMany: {
data: [{ title: 'My first post' }, { title: 'My second post' }],
},
},
},
});

set

set 覆盖关系的值 - 例如,用不同的列表替换 Post 记录的列表。看:与关系合作

¥set overwrites the value of a relation - for example, replacing a list of Post records with a different list. See: Working with relations

示例

¥Examples

通过断开任何先前的 Post 记录并连接另外两个现有记录来更新现有 User 记录

¥Update an existing User record by disconnecting any previous Post records and connecting two other existing ones

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
set: [{ id: 32 }, { id: 42 }],
},
},
});

connect

嵌套 connect 查询通过指定 ID 或唯一标识符将记录连接到现有的相关记录。看:与关系合作

¥A nested connect query connects a record to an existing related record by specifying an ID or unique identifier. See: Working with relations

备注

¥Remarks

  • 当你创建新父记录或更新现有父记录时,connect 可用作嵌套查询。

    ¥connect is available as a nested query when you create a new parent record or update an existing parent record.

  • 如果相关记录不存在,Prisma Client 会抛出异常:

    ¥If the related record does not exist, Prisma Client throws an exception:

    The required connected records were not found. Expected 1 records to be connected, found 0.
  • 当同时使用 setconnect 时,它们的应用顺序会显著影响结果。如果在 connect 之前使用 set,则连接的记录将仅反映 connect 操作建立的最终状态,因为 setconnect 建立新连接之前清除了所有现有连接。相反,如果在 set 之前应用 connectset 操作将通过清除所有连接记录并将其替换为其自己的指定状态来覆盖 connect 操作。

    ¥When using set and connect together, the order in which they are applied significantly impacts the result. If set is used before connect, the connected records will only reflect the final state established by the connect operation, as set clears all existing connections before connect establishes new ones. Conversely, if connect is applied before set, the set operation will override the connect action by clearing all connected records and replacing them with its own specified state.

示例

¥Examples

创建新的 Profile 记录并通过唯一字段将其连接到现有的 User 记录

¥Create a new Profile record and connect it to an existing User record via unique field

const user = await prisma.profile.create({
data: {
bio: 'Hello World',
user: {
connect: { email: 'alice@prisma.io' },
},
},
});
创建新的 Profile 记录并通过 ID 字段将其连接到现有的 User 记录

¥Create a new Profile record and connect it to an existing User record via an ID field

const user = await prisma.profile.create({
data: {
bio: 'Hello World',
user: {
connect: { id: 42 }, // sets userId of Profile record
},
},
});

2.11.0 及以后版本,可以直接设置外键:

¥In 2.11.0 and later, you can set the foreign key directly:

const user = await prisma.profile.create({
data: {
bio: 'Hello World',
userId: 42,
},
});

但是,你不能在同一个查询中同时使用直接方法和 connect 方法。详情请参见 此问题评论

¥However, you can't use both the direct approach and the connect approach in the same query. See this issue comment for details.

创建新的 Post 记录并将其连接到现有的 User 记录

¥Create a new Post record and connect it to an existing User record

const user = await prisma.post.create({
data: {
title: 'Hello World',
author: {
connect: { email: 'alice@prisma.io' },
},
},
});
通过将现有 User 记录连接到现有 Profile 记录来更新现有 User 记录

¥Update an existing User record by connecting it to an existing Profile record

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
profile: {
connect: { id: 24 },
},
},
});
通过将现有 User 记录连接到两个现有 Post 记录来更新该记录

¥Update an existing User record by connecting it to two existing Post records

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
connect: [{ id: 24 }, { id: 42 }],
},
},
});

connectOrCreate

connectOrCreate 通过 ID 或唯一标识符将记录连接到现有的相关记录,或者在记录不存在时创建新的相关记录。看:与关系合作

¥connectOrCreate either connects a record to an existing related record by ID or unique identifier or creates a new related record if the record does not exist. See: Working with relations

备注

¥Remarks

  • 作为并发事务运行的多个 connectOrCreate 查询可能会导致竞争条件。考虑以下示例,其中两个查询尝试同时 connectOrCreate 名为 computing 的博客文章标签(标签名称必须是唯一的):

    ¥Multiple connectOrCreate queries that run as concurrent transactions can result in a race condition. Consider the following example, where two queries attempt to connectOrCreate a blog post tag named computing at the same time (tag names must be unique):

const createPost = await prisma.post.create({
data: {
title: 'How to create a compiler',
content: '...',
author: {
connect: {
id: 9,
},
},
tags: {
connectOrCreate: {
create: {
name: 'computing',
},
where: {
name: 'computing',
},
},
},
},
})

如果查询 A 和查询 B 按以下方式重叠,则查询 A 会导致异常:

¥If query A and query B overlap in the following way, query A results in an exception:

查询 A(失败❌)查询 B(成功✅)
查询命中服务器,启动事务 A查询命中服务器,启动事务 B
查找 tagName 等于 computing 的记录,未找到记录
查找 tagName 等于 computing 的记录,未找到记录
创建 tagName 等于 computing 的记录并连接
创建 tagName 等于 computing 的记录
唯一违规,事务 B 已创建记录

要解决此情况,我们建议捕获唯一的违规异常(PrismaClientKnownRequestError,错误 P2002)并重试失败的查询。

¥To work around this scenario, we recommend catching the unique violation exception (PrismaClientKnownRequestError, error P2002) and retrying failed queries.

示例

¥Examples

创建新的 Profile 记录,然后将其连接到现有的 User 记录或创建新的 User

¥Create a new Profile record, then connect it to an existing User record or create a new User

下面的例子:

¥The following example:

  1. 创建 Profile

    ¥Creates a Profile

  2. 尝试将配置文件连接到电子邮件地址为 alice@prisma.ioUser

    ¥Attempts to connect the profile to a User where the email address is alice@prisma.io

  3. 如果匹配的用户不存在则创建新用户

    ¥Creates a new user if a matching user does not exist

const user = await prisma.profile.create({
data: {
bio: 'The coolest Alice on the planet',
user: {
connectOrCreate: {
where: { email: 'alice@prisma.io' },
create: { email: 'alice@prisma.io'}
},
},
})
创建新的 Post 记录并将其连接到现有的 User 记录,或创建新的 User

¥Create a new Post record and connect it to an existing User record, or create a new User

const user = await prisma.post.create({
data: {
title: 'Hello World',
author: {
connectOrCreate: {
where: { email: 'alice@prisma.io' },
create: { email: 'alice@prisma.io' },
},
},
},
});
通过将现有 User 记录连接到现有 Profile 记录或创建新的 Profile 记录来更新现有 User 记录

¥Update an existing User record by connecting it to an existing Profile record, or creating a new Profile record

下面的例子:

¥The following example:

  1. 尝试将用户连接到具有 id20Profile

    ¥Attempts to connect the user to a Profile with an id of 20

  2. 如果不存在匹配的配置文件,则创建新的配置文件

    ¥Creates a new profile if a matching profile does not exist

const updateUser = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
profile: {
connectOrCreate: {
where: { id: 20 },
create: {
bio: 'The coolest Alice in town',
},
},
},
},
});
通过将现有 User 记录连接到两个现有 Post 记录或创建两个新的 Post 记录来更新现有 User 记录

¥Update an existing User record by connect it to two existing Post records, or creating two new Post records

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
connectOrCreate: [
{
where: { id: 32 },
create: { title: 'This is my first post' },
},
{
where: { id: 19 },
create: { title: 'This is my second post' },
},
],
},
},
});

disconnect

嵌套 disconnect 查询会断开父记录和相关记录之间的连接,但不会删除任何一条记录。看:与关系合作

¥A nested disconnect query breaks the connection between a parent record and a related record, but does not delete either record. See: Working with relations

备注

¥Remarks

  • 仅当关系是可选的时,disconnect 才可用。

    ¥disconnect is only available if the relation is optional.

  • 如果你尝试断开的关系不存在:

    ¥If the relationship you are attempting to disconnect does not exist:

    • (在 2.21.0 及更高版本中),该操作不执行任何操作

      ¥(In 2.21.0 and later), the operation does nothing

    • (2.21.0 之前)如果提供的 ID 或唯一标识符未连接,Prisma 客户端会抛出异常:

      ¥(Before 2.21.0) Prisma Client throws an exception if the provided ID or unique identifier is not connected:

      The records for relation `PostToUser` between the `User` and `Post` models are not connected.

示例

¥Examples

通过断开连接到的 Profile 记录来更新现有 User 记录

¥Update an existing User record by disconnecting the Profile record it's connected to

const user = await prisma.user.update({
where: { email: 'bob@prisma.io' },
data: {
profile: {
disconnect: true,
},
},
});
通过断开连接到的两个 Post 记录来更新现有 User 记录

¥Update an existing User record by disconnecting two Post records it's connected to

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
disconnect: [{ id: 44 }, { id: 46 }],
},
},
});

update

嵌套 update 查询会更新父记录 ID 为 n 的一条或多条相关记录。看:与关系合作

¥A nested update query updates one or more related records where the parent record's ID is n. See: Working with relations

备注

¥Remarks

  • 嵌套 update 查询仅在顶层 update 查询(例如 prisma.user.update(...))的上下文中可用。

    ¥Nested update queries are only available in the context of a top-level update query (for example, prisma.user.update(...)).

  • 如果父记录不存在,Prisma Client 会抛出异常:

    ¥If the parent record does not exist, Prisma Client throws an exception:

    AssertionError("Expected a valid parent ID to be present for nested update to-one case.")
  • 如果你要更新的相关记录不存在,Prisma Client 会抛出异常:

    ¥If the related record that you want to update does not exist, Prisma Client throws an exception:

    AssertionError("Expected a valid parent ID to be present for nested update to-one case.")

示例

¥Examples

通过更新现有的 User 记录连接到的 Profile 记录来更新它

¥Update an existing User record by updating the Profile record it's connected to

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
profile: {
update: { bio: 'Hello World' },
},
},
});
通过更新连接到的两条 Post 记录来更新现有 User 记录

¥Update an existing User record by updating two Post records it's connected to

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
update: [
{
data: { published: true },
where: { id: 32 },
},
{
data: { published: true },
where: { id: 23 },
},
],
},
},
});

upsert

info

本节介绍 update() 中嵌套 upsert 的用法。要了解 upsert() 操作,请参考链接文档。

¥This section covers the usage of nested upsert within update(). To learn about the upsert() operation, reference the linked documentation.

嵌套 upsert 查询会更新相关记录(如果存在),或创建新的相关记录。

¥A nested upsert query updates a related record if it exists, or creates a new related record.

示例

¥Examples

通过更新连接到的 Profile 记录或创建新记录(更新插入)来更新现有 User 记录

¥Update an existing User record by updating the Profile record it's connected to or creating a new one (upsert)

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
profile: {
upsert: {
create: { bio: 'Hello World' },
update: { bio: 'Hello World' },
},
},
},
});
通过更新连接到的两个 Post 记录或创建新记录来更新现有 User 记录(更新插入)

¥Update an existing User record by updating two Post record it's connected to or creating new ones (upsert)

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
upsert: [
{
create: { title: 'This is my first post' },
update: { title: 'This is my first post' },
where: { id: 32 },
},
{
create: { title: 'This is my second post' },
update: { title: 'This is my second post' },
where: { id: 23 },
},
],
},
},
});

delete

嵌套 delete 查询删除相关记录。父记录不会被删除。

¥A nested delete query deletes a related record. The parent record is not deleted.

备注

¥Remarks

  • 仅当关系是可选的时,delete 才可用。

    ¥delete is only available if the relation is optional.

示例

¥Examples

通过删除连接到的 Profile 记录来更新现有 User 记录

¥Update an existing User record by deleting the Profile record it's connected to

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
profile: {
delete: true,
},
},
});
通过删除连接到的两条 Post 记录来更新现有 User 记录

¥Update an existing User record by deleting two Post records it's connected to

const user = await prisma.user.update({
where: { email: 'alice@prisma.io' },
data: {
posts: {
delete: [{ id: 34 }, { id: 36 }],
},
},
});

updateMany

嵌套 updateMany 更新相关记录列表并支持过滤 - 例如,你可以更新用户未发布的帖子。

¥A nested updateMany updates a list of related records and supports filtering - for example, you can update a user's unpublished posts.

示例

¥Examples

更新属于特定用户的所有未发布的帖子

¥Update all unpublished posts belonging to a specific user

const result = await prisma.user.update({
where: {
id: 2,
},
data: {
posts: {
updateMany: {
where: {
published: false,
},
data: {
likes: 0,
},
},
},
},
});

deleteMany

嵌套 deleteMany 删除相关记录并支持过滤。例如,你可以删除用户的帖子,同时更新该用户的其他属性。

¥A nested deleteMany deletes related records and supports filtering. For example, you can delete a user's posts while updating other properties of that user.

示例

¥Examples

作为更新的一部分删除属于特定用户的所有帖子

¥Delete all posts belonging to a specific user as part of an update

const result = await prisma.user.update({
where: {
id: 2,
},
data: {
name: 'Updated name',
posts: {
deleteMany: {},
},
},
});

过滤条件和运算符

¥Filter conditions and operators

equals

值等于 n

¥Value equals n.

示例

¥Examples

返回 name 等于 "Eleanor" 的所有用户

¥Return all users where name equals "Eleanor"

const result = await prisma.user.findMany({
where: {
name: {
equals: 'Eleanor',
},
},
});

你还可以排除 equals

¥You can also exclude the equals:

const result = await prisma.user.findMany({
where: {
name: 'Eleanor',
},
});

返回所有产品低于 "警告数量" 阈值的数量

¥Return all products with a quantity lower than the "warn quantity" threshold

此示例比较了从版本 4.3.0 开始可用的同一模型的字段。

¥This example compares fields of the same model which is available as of version 4.3.0.

const productsWithLowQuantity = await prisma.product.findMany({
where: {
quantity: {
lte: prisma.product.fields.warnQuantity
},
},
});

返回所有以蓝色和绿色为常用颜色的用户

¥Return all users that have blue and green as their favorite colors

此示例查找已将其 favoriteColors 字段设置为 ['blue', 'green'] 的用户。

¥This example finds users that have set their favoriteColors field to ['blue', 'green'].

请注意,使用 equals 时,元素的顺序很重要。也就是说 ['blue', 'green'] 不等于 ['green', 'blue']

¥Note that when using equals, order of elements matters. That is to say ['blue', 'green'] is not equal to ['green', 'blue']

const favoriteColorFriends = await prisma.user.findMany({
where: {
favoriteColors: {
equals: ['blue', 'green'],
},
},
});

not

值不等于 n

¥Value does not equal n.

示例

¥Examples

返回 name 不等于 "Eleanor" 的所有用户

¥Return all users where name does not equal "Eleanor"

const result = await prisma.user.findMany({
where: {
name: {
not: 'Eleanor',
},
},
});
警告

not 将返回与给定值不匹配的所有项目。但是,如果列可以为空,则不会返回 NULL 值。如果你需要返回空值,请使用 OR 运算符包含 NULL 值。

¥not will return all items that do not match a given value. However, if the column is nullable, NULL values will not be returned. If you require null values to be returned, use an OR operator to include NULL values.

返回 name 不等于 "Eleanor" 的所有用户,包括 nameNULL 的用户

¥Return all users where name does not equal "Eleanor" including users where name is NULL

await prisma.user.findMany({
where: {
OR: [
{ name: { not: 'Eleanor' } },
{ name: null }
]
}
})

in

n 存在于列表中。

¥Value n exists in list.

注意

不返回 null 值。例如,如果你结合 inNOT 来返回名称不在列表中的用户,则不会返回具有 null 值名称的用户。

¥null values are not returned. For example, if you combine in and NOT to return a user whose name is not in the list, users with null value names are not returned.

示例

¥Examples

获取 User 条记录,其中 id 可以在以下列表中找到:[22, 91, 14, 2, 5]

¥Get User records where the id can be found in the following list: [22, 91, 14, 2, 5]

const getUser = await prisma.user.findMany({
where: {
id: { in: [22, 91, 14, 2, 5] },
},
});
获取 User 条记录,其中 name 可以在以下列表中找到:['Saqui', 'Clementine', 'Bob']

¥Get User records where the name can be found in the following list: ['Saqui', 'Clementine', 'Bob']

const getUser = await prisma.user.findMany({
where: {
name: { in: ['Saqui', 'Clementine', 'Bob'] },
},
});
获取列表中不存在 nameUser 记录

¥Get User records where name is not present in the list

以下示例结合了 inNOT。你也可以使用 notIn

¥The following example combines in and NOT. You can also use notIn.

const getUser = await prisma.user.findMany({
where: {
NOT: {
name: { in: ['Saqui', 'Clementine', 'Bob'] },
},
},
});
获取一条 User 记录,其中至少一个 Post 至少有一个指定的 Category

¥Get a User record where at least one Post has at least one specified Category

const getUser = await prisma.user.findMany({
where: {
// Find users where..
posts: {
some: {
// ..at least one (some) posts..
categories: {
some: {
// .. have at least one category ..
name: {
in: ['Food', 'Introductions'], // .. with a name that matches one of the following.
},
},
},
},
},
},
});

notIn

列表中不存在值 n

¥Value n does not exist in list.

备注

¥Remarks

  • 不返回 null 值。

    ¥null values are not returned.

示例

¥Examples

获取以下列表中找不到 idUser 条记录:[22, 91, 14, 2, 5]

¥Get User records where the id can not be found in the following list: [22, 91, 14, 2, 5]

const getUser = await prisma.user.findMany({
where: {
id: { notIn: [22, 91, 14, 2, 5] },
},
});

lt

n 小于 x

¥Value n is less than x.

示例

¥Examples

获取所有 Post 记录,其中 likes 小于 9

¥Get all Post records where likes is less than 9

const getPosts = await prisma.post.findMany({
where: {
likes: {
lt: 9,
},
},
});

lte

n 小于或等于 x

¥Value n is less than or equal to x.

示例

¥Examples

获取所有 Post 记录,其中 likes 小于或等于 9

¥Get all Post records where likes is less or equal to 9

const getPosts = await prisma.post.findMany({
where: {
likes: {
lte: 9,
},
},
});

gt

n 大于 x

¥Value n is greater than x.

示例

¥Examples

获取所有 Post 记录,其中 likes 大于 9

¥Get all Post records where likes is greater than 9

const getPosts = await prisma.post.findMany({
where: {
likes: {
gt: 9,
},
},
});

gte

n 大于或等于 x

¥Value n is greater than or equal to x.

示例

¥Examples

获取所有 Post 记录,其中 likes 大于或等于 9

¥Get all Post records where likes is greater than or equal to 9

const getPosts = await prisma.post.findMany({
where: {
likes: {
gte: 9,
},
},
});

示例

¥Examples

获取 date_created 大于 2020 年 3 月 19 日的所有 Post 记录

¥Get all Post records where date_created is greater than March 19th, 2020

const result = await prisma.post.findMany({
where: {
date_created: {
gte: new Date('2020-03-19T14:21:00+0200') /* Includes time offset for UTC */,
},
},
});

contains

n 包含 x

¥Value n contains x.

示例

¥Examples

统计 content 包含 databases 的所有 Post 条记录

¥Count all Post records where content contains databases

const result = await prisma.post.count({
where: {
content: {
contains: 'databases',
},
},
});
统计所有 Post 条记录,其中 content 不包含 databases

¥Count all Post records where content does not contain databases

const result = await prisma.post.count({
where: {
NOT: {
content: {
contains: 'databases',
},
},
},
});

使用 全文搜索String 字段内搜索。

¥Use Full-Text Search to search within a String field.

信息

对于 PostgreSQL,此功能仍处于预览阶段。启用 fullTextSearchPostgres 功能标记 才能使用它。

¥For PostgreSQL, this feature is still in Preview. Enable the fullTextSearchPostgres feature flag in order to use it.

示例

¥Examples

查找标题包含 catdog 的所有帖子。

¥Find all posts with a title that contains cat or dog.

const result = await prisma.post.findMany({
where: {
title: {
search: 'cat | dog',
},
},
});
查找标题包含 catdog 的所有帖子。

¥Find all posts with a title that contains cat and dog.

const result = await prisma.post.findMany({
where: {
title: {
search: 'cat & dog',
},
},
});
查找标题不包含 cat 的所有帖子。

¥Find all posts with a title that doesn't contain cat.

const result = await prisma.post.findMany({
where: {
title: {
search: '!cat',
},
},
});

mode

备注

¥Remarks

  • 仅受 PostgreSQL 和 MongoDB 连接器支持

    ¥Supported by the PostgreSQL and MongoDB connectors only

示例

¥Examples

以不区分大小写的方式获取 title 包含 prisma 的所有 Post 记录

¥Get all Post records where title contains prisma, in a case insensitive way

const result = await prisma.post.findMany({
where: {
title: {
contains: 'prisma',
mode: 'insensitive',
},
},
});

startsWith

示例

¥Examples

获取所有 Post 记录,其中 titlePr 开头(如 Prisma

¥Get all Post records where title starts with Pr (such as Prisma)

const result = await prisma.post.findMany({
where: {
title: {
startsWith: 'Pr',
},
},
});

endsWith

获取所有 User 记录,其中 emailprisma.io 结尾

¥Get all User records where email ends with prisma.io

const result = await prisma.user.findMany({
where: {
email: {
endsWith: 'prisma.io',
},
},
});

AND

所有条件都必须返回 true。或者,将对象列表传递到 where 子句中 - 不需要 AND 运算符

¥All conditions must return true. Alternatively, pass a list of objects into the where clause - the AND operator is not required.

示例

¥Examples

获取所有 Post 记录,其中 content 字段包含 Prismapublishedfalse

¥Get all Post records where the content field contains Prisma and published is false

const result = await prisma.post.findMany({
where: {
AND: [
{
content: {
contains: 'Prisma',
},
},
{
published: {
equals: false,
},
},
],
},
});
获取所有 Post 记录,其中 content 字段包含 Prismapublishedfalse(无 AND

¥Get all Post records where the content field contains Prisma and published is false (no AND)

以下格式返回与前面示例相同的结果(不带 AND 运算符):

¥The following format returns the same results as the previous example without the AND operator:

const result = await prisma.post.findMany({
where: {
content: {
contains: 'Prisma',
},
published: {
equals: false,
},
},
});
获取所有 Post 记录,其中 title 字段包含 Prismadatabases,且 publishedfalse

¥Get all Post records where the title field contains Prisma or databases, and published is false

以下示例结合了 ORAND

¥The following example combines OR and AND:

const result = await prisma.post.findMany({
where: {
OR: [
{
title: {
contains: 'Prisma',
},
},
{
title: {
contains: 'databases',
},
},
],
AND: {
published: false,
},
},
});

OR

一个或多个条件必须返回 true

¥One or more conditions must return true.

示例

¥Examples

获取 title 字段包含 Prismadatabases 的所有 Post 记录

¥Get all Post records where the title field contains Prisma or databases

const result = await prisma.post.findMany({
where: {
OR: [
{
title: {
contains: 'Prisma',
},
},
{
title: {
contains: 'databases',
},
},
],
},
});
获取所有 Post 记录,其中 title 字段包含 Prismadatabases,但不包含 SQL

¥Get all Post records where the title field contains Prisma or databases, but not SQL

以下示例结合了 ORNOT

¥The following example combines OR and NOT:

const result = await prisma.post.findMany({
where: {
OR: [
{
title: {
contains: 'Prisma',
},
},
{
title: {
contains: 'databases',
},
},
],
NOT: {
title: {
contains: 'SQL',
},
},
},
});
获取所有 Post 记录,其中 title 字段包含 Prismadatabases,且 publishedfalse

¥Get all Post records where the title field contains Prisma or databases, and published is false

以下示例结合了 ORAND

¥The following example combines OR and AND:

const result = await prisma.post.findMany({
where: {
OR: [
{
title: {
contains: 'Prisma',
},
},
{
title: {
contains: 'databases',
},
},
],
AND: {
published: false,
},
},
});

NOT

所有条件都必须返回 false

¥All conditions must return false.

示例

¥Examples

获取所有 title 不包含 SQLPost 记录

¥Get all Post records where the title does not contain SQL

const result = await prisma.post.findMany({
where: {
NOT: {
title: {
contains: 'SQL',
},
},
},
});
获取所有 Post 记录,其中 title 字段包含 Prismadatabases,但不包含 SQL,且相关 User 记录的电子邮件地址不包含 sarah

¥Get all Post records where the title field contains Prisma or databases, but not SQL, and the related User record' email address does not contain sarah

const result = await prisma.post.findMany({
where: {
OR: [
{
title: {
contains: 'Prisma',
},
},
{
title: {
contains: 'databases',
},
},
],
NOT: {
title: {
contains: 'SQL',
},
},
user: {
NOT: {
email: {
contains: 'sarah',
},
},
},
},
include: {
user: true,
},
});

关系过滤器

¥Relation filters

some

返回一条或多条 ("some") 相关记录符合过滤条件的所有记录。

¥Returns all records where one or more ("some") related records match filtering criteria.

备注

¥Remarks

  • 你可以使用不带参数的 some 来返回至少具有一个关系的所有记录

    ¥You can use some without parameters to return all records with at least one relation

示例

¥Examples

获取所有 User 记录,其中一些帖子提到 Prisma

¥Get all User records where some posts mention Prisma

const result = await prisma.user.findMany({
where: {
post: {
some: {
content: {
contains: "Prisma"
}
}
}
}
}

every

返回所有 ("every") 条相关记录均符合过滤条件的所有记录。

¥Returns all records where all ("every") related records match filtering criteria.

示例

¥Examples

获取所有发布帖子的所有 User 记录

¥Get all User records where all posts are published

const result = await prisma.user.findMany({
where: {
post: {
every: {
published: true
},
}
}
}

none

返回零个相关记录符合过滤条件的所有记录。

¥Returns all records where zero related records match filtering criteria.

备注

¥Remarks

示例

¥Examples

获取所有 User 条零帖子记录

¥Get all User records with zero posts

const result = await prisma.user.findMany({
where: {
post: {
none: {} // User has no posts
}
}
}
获取所有 User 条记录,其中发布的帖子为零

¥Get all User records with zero published posts

const result = await prisma.user.findMany({
where: {
post: {
none: {
published: true
}
}
}
}

is

返回相关记录符合过滤条件(例如,用户名 is Bob)的所有记录。

¥Returns all records where related record matches filtering criteria (for example, user's name is Bob).

示例

¥Examples

获取用户名为 "Bob" 的所有 Post 记录

¥Get all Post records where user's name is "Bob"

const result = await prisma.post.findMany({
where: {
user: {
is: {
name: "Bob"
},
}
}
}

isNot

返回相关记录不符合过滤条件的所有记录(例如,用户名 isNot Bob)。

¥Returns all records where the related record does not match the filtering criteria (for example, user's name isNot Bob).

示例

¥Examples

获取用户名不是 "Bob" 的所有 Post 记录

¥Get all Post records where user's name is NOT "Bob"

const result = await prisma.post.findMany({
where: {
user: {
isNot: {
name: "Bob"
},
}
}
}

标量列表方法

¥Scalar list methods

set

使用 set 覆盖标量列表字段的值。

¥Use set to overwrite the value of a scalar list field.

备注

¥Remarks

  • set 是可选的 - 你可以直接设置该值:

    ¥set is optional - you can set the value directly:

    tags: ['computers', 'books'];

示例

¥Examples

tags 的值设置为字符串值列表

¥Set the value of tags to a list of string values

const setTags = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
set: ['computing', 'books'],
},
},
});
tags 设置为值列表,而不使用 set 关键字

¥Set tags to a list of values without using the set keyword

const setTags = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: ['computing', 'books'],
},
});

tags 的值设置为单个字符串值

¥Set the value of tags to a single string value

const setTags = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
set: 'computing',
},
},
});

push

push2.20.0 及更高版本中可用。使用 push 将一个或多个值添加到标量列表字段。

¥push is available in version 2.20.0 and later. Use push to add one value or multiple values to a scalar list field.

备注

¥Remarks

  • 仅适用于 PostgreSQL 和 MongoDB。

    ¥Available for PostgreSQL and MongoDB only.

  • 你可以推送值列表或仅推送单个值。

    ¥You can push a list of values or only a single value.

示例

¥Examples

computing 项目添加到 tags 列表

¥Add a computing item to the tags list

const addTag = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
push: 'computing',
},
},
});
const addTag = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
push: ['computing', 'genetics'],
},
},
});

unset

warning

该方法仅适用于 MongoDB 3.11.1 及更高版本。

¥This method is available on MongoDB only in versions 3.11.1 and later.

使用 unset 取消设置标量列表的值。与 set: null 不同,unset 完全删除了该列表。

¥Use unset to unset the value of a scalar list. Unlike set: null, unset removes the list entirely.

示例

¥Examples

取消设置 tags 的值

¥Unset the value of tags

const setTags = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
unset: true,
},
},
});

标量列表过滤器

¥Scalar list filters

标量列表过滤器允许你按列表/数组字段的内容进行过滤。

¥Scalar list filters allow you to filter by the contents of a list / array field.

warning

可以用来:

¥Available for:

  • 2.15.0 及更高版本的 PostgreSQL

    ¥PostgreSQL in versions 2.15.0 and later

  • 3.9.0 及更高版本中的 CockroachDB

    ¥CockroachDB in versions 3.9.0 and later

  • 版本 3.11.0 及更高版本的 MongoDB

    ¥MongoDB in versions 3.11.0 and later

备注

¥Remarks

  • 标量列表/数组过滤器 忽略 NULL 。 使用 isEmptyNOT 不会返回具有 NULL 值列表/数组的记录,并且 { equals: null } 会导致错误。

    ¥Scalar list / array filters ignore NULL values . Using isEmpty or NOT does not return records with NULL value lists / arrays, and { equals: null } results in an error.

has

给定值存在于列表中。

¥The given value exists in the list.

示例

¥Examples

以下查询返回 tags 列表中包含 "databases" 的所有 Post 记录:

¥The following query returns all Post records where the tags list includes "databases":

const posts = await client.post.findMany({
where: {
tags: {
has: 'databases',
},
},
});

以下查询返回所有 Post 记录,其中 tags 列表不包含 "databases"

¥The following query returns all Post records where the tags list does not include "databases":

const posts = await client.post.findMany({
where: {
NOT: {
tags: {
has: 'databases',
},
},
},
});

hasEvery

每个值都存在于列表中。

¥Every value exists in the list.

示例

¥Examples

以下查询返回所有 Post 记录,其中 tags 列表至少包含 "databases""typescript"

¥The following query returns all Post records where the tags list includes at least "databases" and "typescript":

const posts = await prisma.post.findMany({
where: {
tags: {
hasEvery: ['databases', 'typescript'],
},
},
});

hasSome

列表中至少存在一个值。

¥At least one value exists in the list.

示例

¥Examples

以下查询返回 tags 列表中包含 "databases""typescript" 的所有 Post 记录:

¥The following query returns all Post records where the tags list includes "databases" or "typescript":

const posts = await prisma.post.findMany({
where: {
tags: {
hasSome: ['databases', 'typescript'],
},
},
});

isEmpty

该列表为空。

¥The list is empty.

示例

¥Examples

以下查询返回所有没有标签的 Post 记录:

¥The following query returns all Post records that have no tags:

const posts = await prisma.post.findMany({
where: {
tags: {
isEmpty: true,
},
},
});

isSet

warning

此过滤器仅在 MongoDB 版本 3.11.1 及更高版本中可用。

¥This filter is available on MongoDB only in versions 3.11.1 and later.

过滤器列表仅包含已设置的结果(设置为某个值,或显式设置为 null)。将此过滤器设置为 true 将排除根本未设置的未定义结果。

¥Filter lists to include only results that have been set (either set to a value, or explicitly set to null). Setting this filter to true will exclude undefined results that are not set at all.

示例

¥Examples

以下查询返回所有 Post 记录,其中 tags 已设置为 null 或某个值:

¥The following query returns all Post records where the tags have been set to either null or a value:

const posts = await prisma.post.findMany({
where: {
tags: {
isSet: true,
},
},
});

equals

该列表与给定值完全匹配。

¥The list matches the given value exactly.

示例

¥Examples

以下查询返回所有 Post 记录,其中 tags 列表仅包含 "databases""typescript"

¥The following query returns all Post records where the tags list includes "databases" and "typescript" only:

const posts = await prisma.post.findMany({
where: {
tags: {
equals: ['databases', 'typescript'],
},
},
});

复合类型方法

¥Composite type methods

warning

仅适用于 Prisma 3.10.0 及更高版本中的 MongoDB。

¥Available for MongoDB only in Prisma 3.10.0 and later.

复合类型方法允许你创建、更新和删除 复合类型

¥Composite type methods allow you to create, update and delete composite types.

set

使用 set 覆盖复合类型的值。

¥Use set to overwrite the value of a composite type.

备注

¥Remarks

  • set 关键字是可选的 - 你可以直接设置该值:

    ¥The set keyword is optional - you can set the value directly:

    photos: [
    { height: 100, width: 200, url: '1.jpg' },
    { height: 100, width: 200, url: '2.jpg' },
    ];

示例

¥Examples

在新的 order 中设置 shippingAddress 复合类型

¥Set the shippingAddress composite type within a new order

const order = await prisma.order.create({
data: {
// Normal relation
product: { connect: { id: 'some-object-id' } },
color: 'Red',
size: 'Large',
// Composite type
shippingAddress: {
set: {
street: '1084 Candycane Lane',
city: 'Silverlake',
zip: '84323',
},
},
},
});
将可选复合类型设置为 null

¥Set an optional composite type to null

const order = await prisma.order.create({
data: {
// Embedded optional type, set to null
billingAddress: {
set: null,
},
},
});

unset

使用 unset 取消设置复合类型的值。与 set: null 不同,这会从 MongoDB 文档中完全删除该字段。

¥Use unset to unset the value of a composite type. Unlike set: null, this removes the field entirely from the MongoDB document.

示例

¥Examples

order 中移除 billingAddress

¥Remove the billingAddress from an order

const order = await prisma.order.update({
where: {
id: 'some-object-id',
},
data: {
billingAddress: {
// Unset the billing address
// Removes "billingAddress" field from order
unset: true,
},
},
});

update

使用 update 更新所需复合类型中的字段。

¥Use update to update fields within a required composite type.

备注

¥Remarks

update 方法不能用于可选类型。相反,使用 upsert

¥The update method cannot be used on optional types. Instead, use upsert

示例

¥Examples

更新 shippingAddress 复合类型的 zip 字段

¥Update the zip field of a shippingAddress composite type

const order = await prisma.order.update({
where: {
id: 'some-object-id',
},
data: {
shippingAddress: {
// Update just the zip field
update: {
zip: '41232',
},
},
},
});

upsert

使用 upsert 更新现有的可选复合类型(如果存在),否则设置复合类型。

¥Use upsert to update an existing optional composite type if it exists, and otherwise set the composite type.

备注

¥Remarks

upsert 方法不能用于所需类型。相反,使用 update

¥The upsert method cannot be used on required types. Instead, use update

示例

¥Examples

如果 billingAddress 不存在则创建一个新的,否则更新它

¥Create a new billingAddress if it doesn't exist, and otherwise update it

const order = await prisma.order.update({
where: {
id: 'some-object-id',
},
data: {
billingAddress: {
// Create the address if it doesn't exist,
// otherwise update it
upsert: {
set: {
street: '1084 Candycane Lane',
city: 'Silverlake',
zip: '84323',
},
update: {
zip: '84323',
},
},
},
},
});

push

使用 push 将值推送到复合类型列表的末尾。

¥Use push to push values to the end of a list of composite types.

示例

¥Examples

将新照片添加到 photos 列表

¥Add a new photo to the photos list

const product = prisma.product.update({
where: {
id: 10,
},
data: {
photos: {
// Push a photo to the end of the photos list
push: [{ height: 100, width: 200, url: '1.jpg' }],
},
},
});

复合型过滤器

¥Composite type filters

warning

仅适用于 Prisma 3.11.0 及更高版本中的 MongoDB。

¥Available for MongoDB only in Prisma 3.11.0 and later.

复合类型过滤器允许你过滤 复合类型 的内容。

¥Composite type filters allow you to filter the contents of composite types.

equals

使用 equals 通过匹配复合类型或复合类型列表来过滤结果。要求复合类型的所有必填字段都匹配。

¥Use equals to filter results by matching a composite type or a list of composite types. Requires all required fields of the composite type to match.

备注

¥Remarks

匹配可选字段时,需要区分文档中未定义(缺失)的字段和已显式设置为 null 的字段:

¥When matching optional fields, you need to distinguish between undefined (missing) fields of the document, and fields that have been explicitly set to null:

  • 如果省略可选字段,它将匹配未定义的字段,但不匹配已设置为 null 的字段

    ¥If you omit an optional field, it will match undefined fields, but not fields that have been set to null

  • 如果你使用 equals: { ... exampleField: null ... } 过滤可选字段的 null 值,则它将仅匹配该字段已设置为 null 的文档,而不匹配未定义的字段

    ¥If you filter for null values of an optional field with equals: { ... exampleField: null ... }, then it will match only documents where the field has been set to null, and not undefined fields

使用 equals 时,字段和列表的顺序很重要:

¥The ordering of fields and lists matters when using equals:

  • 对于字段,{ "a": "1", "b": "2" }{ "b": "2", "a": "1" } 不被视为相等

    ¥For fields, { "a": "1", "b": "2" } and { "b": "2", "a": "1" } are not considered equal

  • 对于列表,[ { "a": 1 }, { "a": 2 } ][ { "a": 2 }, { "a": 1 } ] 不被视为相等

    ¥For lists, [ { "a": 1 }, { "a": 2 } ] and [ { "a": 2 }, { "a": 1 } ] are not considered equal

示例

¥Examples

查找与给定 shippingAddress 完全匹配的订单

¥Find orders that exactly match the given shippingAddress

const orders = await prisma.order.findMany({
where: {
shippingAddress: {
equals: {
street: '555 Candy Cane Lane',
city: 'Wonderland',
zip: '52337',
},
},
},
});
查找照片与所有 url 列表相匹配的产品

¥Find products with photos that match all of a list of urls

const product = prisma.product.findMany({
where: {
equals: {
photos: [{ url: '1.jpg' }, { url: '2.jpg' }],
},
},
});

is

使用 is 通过匹配复合类型中的特定字段来过滤结果。

¥Use is to filter results by matching specific fields within composite types.

示例

¥Examples

查找 shippingAddress 与给定街道名称匹配的订单

¥Find orders with a shippingAddress that matches the given street name

const orders = await prisma.order.findMany({
where: {
shippingAddress: {
is: {
street: '555 Candy Cane Lane',
},
},
},
});

isNot

使用 isNot 过滤结果中不匹配的复合类型字段。

¥Use isNot to filter results for composite type fields that do not match.

示例

¥Examples

查找 shippingAddress 与给定邮政编码不匹配的订单

¥Find orders with a shippingAddress that does not match the given zip code

const orders = await prisma.order.findMany({
where: {
shippingAddress: {
isNot: {
zip: '52337',
},
},
},
});

isEmpty

使用 isEmpty 筛选复合类型空列表的结果。

¥Use isEmpty to filter results for an empty list of composite types.

示例

¥Examples

查找没有照片的产品

¥Find products with no photos

const product = prisma.product.findMany({
where: {
photos: {
isEmpty: true,
},
},
});

every

使用 every 过滤复合类型列表,其中列表中的每个项目都符合条件

¥Use every to filter for lists of composite types where every item in the list matches the condition

示例

¥Examples

找到第一个每张照片都有 height200 的产品

¥Find the first product where every photo has a height of 200

const product = await prisma.product.findFirst({
where: {
photos: {
every: {
height: 200,
}
}
},
})

some

使用 some 筛选复合类型列表,其中列表中的一项或多项符合条件。

¥Use some to filter for lists of composite types where one or more items in the list match the condition.

示例

¥Examples

查找第一个其中一张或多张照片的 url2.jpg 的产品

¥Find the first product where one or more photos have a url of 2.jpg

const product = await prisma.product.findFirst({
where: {
photos: {
some: {
url: "2.jpg",
}
}
},
})

none

使用 none 筛选复合类型列表,其中列表中没有项目与条件匹配。

¥Use none to filter for lists of composite types where no items in the list match the condition.

示例

¥Examples

查找第一个没有照片具有 url2.jpg 的产品

¥Find the first product where no photos have a url of 2.jpg

const product = await prisma.product.findFirst({
where: {
photos: {
none: {
url: "2.jpg",
}
}
},
})

原子序数运算

¥Atomic number operations

更新时的原子操作可用于数字字段类型(FloatInt)。此功能允许你根据字段的当前值(例如减法或除法)更新字段,而不会面临竞争条件的风险。

¥Atomic operations on update is available for number field types (Float and Int). This feature allows you to update a field based on its current value (such as subtracting or dividing) without risking a race condition.

Overview: Race conditions

当必须按顺序完成两个或多个操作才能完成任务时,就会出现竞争条件。在以下示例中,两个客户端尝试将同一字段 (postCount) 加一:

¥A race conditions occurs when two or more operations must be done in sequence in order to complete a task. In the following example, two clients try to increase the same field (postCount) by one:

客户操作
客户 1获取字段值21
客户 2获取字段值21
客户 2设置字段值22
客户 1设置字段值22

该值应该是 23,但是两个客户端没有按顺序读写 postCount 字段。更新时的原子操作将读取和写入合并为单个操作,这可以防止竞争条件:

¥The value should be 23, but the two clients did not read and write to the postCount field in sequence. Atomic operations on update combine read and write into a single operation, which prevents a race condition:

客户操作
客户 1获取和设置字段值2122
客户 2获取和设置字段值2223

运算符

¥Operators

选项描述
incrementn 添加到当前值。
decrement从当前值中减去 n
multiply将当前值乘以 n
divide将当前值除以 n
set设置当前字段值。与 { myField : n } 相同。

备注

¥Remarks

  • 对于每个查询,每个字段只能执行一次原子更新。

    ¥You can only perform one atomic update per field, per query.

  • 如果字段为 null,则 incrementdecrementmultiplydivide 不会更新该字段。

    ¥If a field is null, it will not be updated by increment, decrement, multiply, or divide.

示例

¥Examples

将所有 Post 记录的所有 viewlikes 字段增加 1

¥Increment all view and likes fields of all Post records by 1

const updatePosts = await prisma.post.updateMany({
data: {
views: {
increment: 1,
},
likes: {
increment: 1,
},
},
});

将所有 Post 记录的所有 views 字段设置为 0

¥Set all views fields of all Post records to 0

const updatePosts = await prisma.post.updateMany({
data: {
views: {
set: 0,
},
},
});

也可以写成:

¥Can also be written as:

const updatePosts = await prisma.post.updateMany({
data: {
views: 0,
},
});

Json 过滤器

¥Json filters

有关用例和高级示例,请参阅:使用 Json 字段

¥For use cases and advanced examples, see: Working with Json fields.

warning

PostgreSQLMySQL 支持,path 选项具有不同的语法。PostgreSQL 不支持对数组中的对象键值进行过滤。

¥Supported by PostgreSQL and MySQL with different syntaxes for the path option. PostgreSQL does not support filtering on object key values in arrays.

本节中的示例假设 pet 字段的值为:

¥The examples in this section assumes that the value of the pet field is:

{
"favorites": {
"catBreed": "Turkish van",
"dogBreed": "Rottweiler",
"sanctuaries": ["RSPCA", "Alley Cat Allies"],
"treats": [
{ "name": "Dreamies", "manufacturer": "Mars Inc" },
{ "name": "Treatos", "manufacturer": "The Dog People" }
]
},
"fostered": {
"cats": ["Bob", "Alice", "Svetlana the Magnificent", "Queenie"]
},
"owned": {
"cats": ["Elliott"]
}
}

备注

¥Remarks

path

path 代表特定键的位置。以下查询返回嵌套 favourites > dogBreed 键等于 "Rottweiler" 的所有用户。

¥path represents the location of a specific key. The following query returns all users where the nested favourites > dogBreed key equals "Rottweiler".

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['favorites', 'dogBreed'],
equals: 'Rottweiler',
},
},
});

以下查询返回嵌套 owned > cats 数组包含 "Elliott" 的所有用户。

¥The following query returns all users where the nested owned > cats array contains "Elliott".

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['owned', 'cats'],
array_contains: ['Elliott'],
},
},
});
warning

仅 MySQL 连接器支持按数组内对象的键值进行过滤(如下)。

¥Filtering by the key values of objects inside an array (below) is only supported by the MySQL connector.

以下查询返回嵌套 favorites > treats 数组包含 name 值为 "Dreamies" 的对象的所有用户:

¥The following query returns all users where the nested favorites > treats array contains an object where the name value is "Dreamies":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: '$.favorites.treats[*].name',
array_contains: 'Dreamies',
},
},
});

string_contains

以下查询返回嵌套 favorites > catBreed 键值包含 "Van" 的所有用户:

¥The following query returns all users where the nested favorites > catBreed key value contains "Van":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['favorites', 'catBreed'],
string_contains: 'Van',
},
},
});

string_starts_with

以下查询返回嵌套 favorites > catBreed 键值以 "Turkish" 开头的所有用户:

¥The following query returns all users where the nested favorites > catBreed key value starts with "Turkish":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['favorites', 'catBreed'],
string_starts_with: 'Turkish',
},
},
});

string_ends_with

以下查询返回嵌套 favorites > catBreed 键值以 "Van" 结尾的所有用户:

¥The following query returns all users where the nested favorites > catBreed key value ends with "Van":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['favorites', 'catBreed'],
string_ends_with: 'Van',
},
},
});

mode

指定字符串过滤是否应区分大小写(默认)或不区分大小写。

¥Specify whether the the string filtering should be case sensitive (default) or case insensitive.

以下查询返回嵌套 favorites > catBreed 键值包含 "Van""van" 的所有用户:

¥The following query returns all users where the nested favorites > catBreed key value contains "Van" or "van":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['favorites', 'catBreed'],
string_contains: 'Van',
mode: "insensitive",
},
},
});

array_contains

以下查询返回 sanctuaries 数组包含值 "RSPCA" 的所有用户:

¥The following query returns all users where the sanctuaries array contains the value "RSPCA":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['sanctuaries'],
array_contains: ['RSPCA'],
},
},
});
info

Note: In PostgreSQL, the value of array_contains must be an array and not a string, even if the array only contains a single value.

以下查询返回 sanctuaries 数组包含给定数组中所有值的所有用户:

¥The following query returns all users where the sanctuaries array contains all the values in the given array:

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['sanctuaries'],
array_contains: ['RSPCA', 'Alley Cat Allies'],
},
},
});

array_starts_with

以下查询返回 sanctuaries 数组以值 "RSPCA" 开头的所有用户:

¥The following query returns all users where the sanctuaries array starts with the value "RSPCA":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['sanctuaries'],
array_starts_with: 'RSPCA',
},
},
});

array_ends_with

以下查询返回 sanctuaries 数组以值 "Alley Cat Allies" 结尾的所有用户:

¥The following query returns all users where the sanctuaries array ends with the value "Alley Cat Allies":

const getUsers = await prisma.user.findMany({
where: {
pets: {
path: ['sanctuaries'],
array_ends_with: 'Alley Cat Allies',
},
},
});

客户端方法

¥Client methods

注意:客户端级方法以 $ 为前缀。

¥Note: Client-level methods are prefixed by $.

备注

¥Remarks

  • 使用 $extends 扩展的扩展客户端实例上不存在 $on$use 客户端方法

    ¥$on and $use client methods do not exist on extended client instances which are extended using $extends

warning

扩展客户 中,Client 方法不一定存在。如果你要扩展客户端,请确保在使用 $transaction$connect 等客户端方法之前检查是否存在。

¥In extended clients, Client methods do not necessarily exist. If you are extending your client, make sure to check for existence before using Client methods like $transaction or $connect.

此外,如果你使用 $on$use,则需要在扩展客户端之前使用这些客户端方法,因为扩展客户端上不存在这些方法。对于 $use,我们特别建议转换 使用查询扩展

¥In addition, if you are using $on or $use, you will need to use these client methods before extending your client as these methods do not exist on extended clients. For $use specifically we recommend transitioning to use query extensions.

$disconnect()

$disconnect() 方法关闭调用 $connect 时建立的数据库连接,并停止运行 Prisma ORM 查询引擎的进程。有关 $connect()$disconnect() 的概述,请参阅 连接管理

¥The $disconnect() method closes the database connections that were established when $connect was called and stops the process that was running Prisma ORM's query engine. See Connection management for an overview of $connect() and $disconnect().

备注

¥Remarks

  • $disconnect() 返回 Promise,因此你应该在 async 函数内使用 await 关键字调用它。

    ¥$disconnect() returns a Promise, so you should call it inside an async function with the await keyword.

$connect()

$connect() 方法通过 Prisma ORM 的查询引擎建立与数据库的物理连接。有关 $connect()$disconnect() 的概述,请参阅 连接管理

¥The $connect() method establishes a physical connection to the database via Prisma ORM's query engine. See Connection management for an overview of $connect() and $disconnect().

备注

¥Remarks

  • $connect() 返回 Promise,因此你应该在 async 函数内使用 await 关键字调用它。

    ¥$connect() returns a Promise, so you should call it inside an async function with the await keyword.

$on()

warning

$on扩展客户 中不可用。请迁移到客户端扩展或在扩展客户端之前使用 $on 方法。

¥$on is not available in extended clients. Please either migrate to client extensions or use the $on method prior to extending your client.

$on() 方法允许你订阅 记录事件退出钩子

¥The $on() method allows you to subscribe to logging events or the exit hook.

$use()

warning

$use扩展客户 中不可用。在扩展你的客户之前,请 要么迁移到查询扩展 或使用 $use 方法。

¥$use is not available in extended clients. Please either migrate to query extensions or use the $use method prior to extending your client.

$use() 方法添加 中间件

¥The $use() method adds middleware :

prisma.$use(async (params, next) => {
console.log('This is middleware!');
// Modify or interrogate params here

return next(params);
});

next

next 代表中间件堆栈中的 "下一级",它可能是下一个中间件或 Prisma Query,具体取决于 你在堆栈中的哪个位置

¥next represents the "next level" in the middleware stack, which could be the next middleware or the Prisma Query, depending on where in the stack you are.

params

params 是一个包含在中间件中使用的信息的对象。

¥params is an object with information to use in your middleware.

范围描述
action查询类型 - 例如,createfindMany
args传递到查询中的参数 - 例如,wheredataorderBy
dataPath如果你使用 流畅的 API,则已填充。
model型号类型 - 例如,PostUser
runInTransaction如果查询在 transaction 的上下文中运行,则返回 true
提示

如果你需要 model 属性作为字符串,请使用:String(params.model)

¥If you need the model property as a string, use: String(params.model)

参数值示例:

¥Example parameter values:

{
args: { where: { id: 15 } },
dataPath: [ 'select', 'author', 'select', 'posts' ],
runInTransaction: false,
action: 'findMany',
model: 'Post'
}

示例

¥Examples

参见 中间件示例

¥See middleware examples.

$queryRawTyped

看:使用原始 SQL ($queryRawTyped)

¥See: Using Raw SQL ($queryRawTyped).

$queryRaw

看:使用原始 SQL ($queryRaw)

¥See: Using Raw SQL ($queryRaw).

$queryRawUnsafe()

看:使用原始 SQL ($queryRawUnsafe())

¥See: Using Raw SQL ($queryRawUnsafe()).

$executeRaw

看:使用原始 SQL ($executeRaw)

¥See: Using Raw SQL ($executeRaw).

$executeRawUnsafe()

看:使用原始 SQL ($executeRawUnsafe())

¥See: Using Raw SQL ($executeRawUnsafe()).

$runCommandRaw()

看:使用原始 SQL ($runCommandRaw())

¥See: Using Raw SQL ($runCommandRaw()).

$transaction()

看:事务

¥See: Transactions.

$metrics

Prisma 客户端指标可让你详细了解 Prisma 客户端如何与数据库交互。你可以使用此见解来帮助诊断应用的性能问题。了解更多:指标

¥Prisma Client metrics give you a detailed insight into how Prisma Client interacts with your database. You can use this insight to help diagnose performance issues with your application. Learn more: Metrics.

Prisma Client 指标有以下方法:

¥Prisma Client metrics has the following methods:

$extends

使用 $extends,你可以通过以下方式创建和使用 Prisma 客户端扩展来向 Prisma 客户端添加功能:

¥With $extends, you can create and use Prisma Client extensions to add functionality to Prisma Client in the following ways:

  • model:将自定义方法添加到你的模型中

    ¥model: add custom methods to your models

  • client:向你的客户端添加自定义方法

    ¥client: add custom methods to your client

  • query:创建自定义 Prisma 客户端查询

    ¥query: create custom Prisma Client queries

  • result:将自定义字段添加到你的查询结果中

    ¥result: add custom fields to your query results

了解更多:Prisma 客户端扩展

¥Learn more: Prisma Client extensions.

工具类型

¥Utility types

工具类型是位于 Prisma 命名空间中的辅助函数和类型。它们对于保证应用类型的安全很有用。

¥Utility types are helper functions and types that live on the Prisma namespace. They are useful for keeping your application type safe.

Prisma.validator

validator 可帮助你根据架构模型创建可重用的查询参数,同时确保你创建的对象有效。也可以看看:使用 Prisma.validator

¥The validator helps you create re-usable query parameters based on your schema models while making sure that the objects you create are valid. See also: Using Prisma.validator

你可以通过两种方式使用 validator

¥There are two ways you can use the validator:

使用生成的 Prisma 客户端类型

¥Using generated Prisma Client types

使用类型提供了一种类型级方法来验证数据:

¥Using types provides a type-level approach to validate data:

Prisma.validator<GeneratedType>({ args });

使用 "selector"

¥Using a "selector"

使用选择器模式时,你可以使用现有的 Prisma 客户端实例来创建验证器。此模式允许你选择要验证的模型、操作和查询选项。

¥When using the selector pattern, you use an existing Prisma Client instance to create a validator. This pattern allows you to select the model, operation, and query option to validate against.

你还可以使用已使用 Prisma 客户端扩展 扩展的 Prisma 客户端实例。

¥You can also use an instance of Prisma Client that has been extended using a Prisma Client extension.

Prisma.validator(PrismaClientInstance, '<model>', '<operation>', '<query option>')({ args });

示例

¥Examples

以下示例展示了如何提取和验证可在应用中重复使用的 create 操作的输入:

¥The following example shows how you can extract and validate the input for the create operation you can reuse within your app:

import { Prisma } from '@prisma/client';

const validateUserAndPostInput = (name, email, postTitle) => {
return Prisma.validator<Prisma.UserCreateInput>()({
name,
email,
posts: {
create: {
title: postTitle,
},
},
});
};

以下是同一操作的替代语法:

¥Here is an alternative syntax for the same operation:

import { Prisma } from '@prisma/client';
import prisma from './prisma';

const validateUserAndPostInput = (name, email, postTitle) => {
return Prisma.validator(
prisma,
'user',
'create',
'data'
)({
name,
email,
posts: {
create: {
title: postTitle,
},
},
});
};

比较同一个表中的列

¥Compare columns in the same table

对于非唯一过滤器,你可以直接比较同一表中的列。

¥You can compare columns in the same table directly, for non-unique filters.

此功能已在版本 5.0.0 中移至通用版本,并可通过 Prisma ORM 版本 4.3.0 至 4.16.2 的 fieldReference 预览功能使用。

¥This feature was moved to general availability in version 5.0.0 and was available via the fieldReference Preview feature from Prisma ORM versions 4.3.0 to 4.16.2.

info

在以下情况下,你必须 使用原始查询来比较同一个表中的列

¥In the following situations, you must use raw queries to compare columns in the same table:

  • 如果你使用 4.3.0 之前的版本

    ¥If you use a version earlier than 4.3.0

  • 如果你想使用唯一的过滤器,例如 findUniquefindUniqueOrThrow

    ¥If you want to use a unique filter, such as findUnique or findUniqueOrThrow

  • 如果你想将某个字段与 唯一约束 进行比较

    ¥If you want to compare a field with a unique constraint

  • 如果你想使用以下运算符之一将 MySQL 或 MariaDB 中的 JSON 字段 与另一个字段进行比较:gtgteltlte。请注意,你可以使用这些运算符将 JSON 字段与标量值进行比较。仅当你尝试将 JSON 字段与另一个字段进行比较时,此限制才适用。

    ¥If you want to use one of the following operators to compare a JSON field in MySQL or MariaDB with another field: gt, gte, lt, or lte. Note that you can use these operators to compare the JSON field with a scalar value. This limitation applies only if you try to compare a JSON field with another field.

要比较同一表中的列,请使用 <model>.fields 属性。在以下示例中,查询返回 prisma.product.quantity 字段中的值小于或等于 prisma.product.warnQuantity 字段中的值的所有记录。

¥To compare columns in the same table, use the <model>.fields property. In the following example, the query returns all records where the value in the prisma.product.quantity field is less than or equal to the value in the prisma.product.warnQuantity field.

prisma.product.findMany({
where: { quantity: { lte: prisma.product.fields.warnQuantity } },
});
info

fields 是每个型号的特殊属性。它包含该模型的字段列表。

¥fields is a special property of every model. It contains the list of fields for that model.

注意事项

¥Considerations

字段必须属于同一类型

¥Fields must be of the same type

你只能对相同类型的字段进行比较。例如,以下情况会导致错误:

¥You can only make comparisons on fields of the same type. For example, the following causes an error:

await prisma.order.findMany({
where: {
id: { equals: prisma.order.fields.due },
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Type error: id is a string, while amountDue is an integer
},
});

字段必须位于同一模型中

¥Fields must be in the same model

你只能与同一模型中字段的 fields 属性进行比较。下面的例子不起作用:

¥You can only make comparisons with the fields property on fields in the same model. The following example does not work:

await prisma.order.findMany({
where: {
id: { equals: prisma.user.fields.name },
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Type error: name is a field on the User model, not Order
},
});

但是,你可以将单独模型中的字段与 标准查询 进行比较。

¥However, you can compare fields in separate models with standard queries.

groupBy 模型查询中,将引用的字段放入 by 参数中

¥In groupBy model queries, put your referenced fields in the by argument

如果你将 groupBy 模型查询与 having 选项一起使用,则必须将引用的字段放在 by 参数中。

¥If you use the groupBy model query with the having option, then you must put your referenced fields in the by argument.

以下示例有效:

¥The following example works:

prisma.user.groupBy({
by: ['id', 'name'],
having: { id: { equals: prisma.user.fields.name } },
});

以下示例不起作用,因为 name 不在 by 参数中:

¥The following example does not work, because name is not in the by argument:

prisma.user.groupBy({
by: ['id'],
having: { id: { equals: prisma.user.fields.name } },
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// name is not in the 'by' argument
});

在标量列表中搜索字段

¥Search for fields in scalar lists

如果你的数据源支持标量列表(例如在 PostgreSQL 中),则你可以搜索特定字段位于字段列表中的所有记录。为此,请使用 innotIn 过滤器引用标量列表。例如:

¥If your data source supports scalar lists (for example in PostgreSQL), then you can search for all records where a specific field is in a list of fields. To do so, reference the scalar list with the in and notIn filters. For example:

await prisma.user.findMany({
where: {
// find all users where 'name' is in a list of tags
name: { in: prisma.user.fields.tags },
},
});

使用 UserWhereUniqueInput 过滤非唯一字段

¥Filter on non-unique fields with UserWhereUniqueInput

从版本 5.0.0 开始,where 上生成的类型 UserWhereUniqueInput 公开模型上的所有字段,而不仅仅是唯一字段。这在 extendedWhereUnique 预览标志 版本 4.5.0 到 4.16.2 之间可用

¥From version 5.0.0, the generated type UserWhereUniqueInput on where exposes all fields on the model, not just unique fields. This was available under the extendedWhereUnique Preview flag between versions 4.5.0 to 4.16.2

你必须在 where 语句 布尔运算符之外 中至少指定一个唯一字段,并且可以指定任意数量的附加唯一字段和非唯一字段。你可以使用它向任何返回单个记录的操作添加过滤器。例如,你可以将此功能用于以下用途:

¥You must specify at least one unique field in your where statement outside of boolean operators, and you can specify any number of additional unique and non-unique fields. You can use this to add filters to any operation that returns a single record. For example, you can use this feature for the following:

从版本 4.6.0 开始,你可以使用此功能来过滤可选的 一对一嵌套读取

¥From version 4.6.0, you can use this feature to filter on optional one-to-one nested reads.

更新的乐观并发控制

¥Optimistic concurrency control on updates

你可以过滤非唯一字段以对 update 执行 乐观并发控制 操作。

¥You can filter on non-unique fields to perform optimistic concurrency control on update operations.

为了进行乐观并发控制,我们建议你使用 version 字段来检查代码执行时记录或相关记录中的数据是否发生变化。在版本 4.5.0 之前,你无法在 update 操作中计算 version 字段,因为该字段不是唯一的。从版本 4.5.0 开始,你可以评估 version 字段。

¥To perform optimistic concurrency control, we recommend that you use a version field to check whether the data in a record or related record has changed while your code executes. Before version 4.5.0, you could not evaluate the version field in an update operation, because the field is non-unique. From version 4.5.0, you can evaluate the version field.

在以下示例中,updateOneupdateTwo 首先读取相同的记录,然后尝试更新它。仅当 version 中的值与初始读取时的值相同时,数据库才会执行这些更新。当数据库执行第一次更新时(可能是 updateOneupdateTwo,具体取决于时间),它会增加 version 中的值。这意味着数据库不会执行第二次更新,因为 version 中的值已更改。

¥In the following example, updateOne and updateTwo first read the same record and then attempt to update it. The database only executes these updates if the value in version is the same as the value when it did the initial read. When the database executes the first of these updates (which might be updateOne or updateTwo, depending on timing), it increments the value in version. This means that the database does not execute the second update because the value in version has changed.

model User {
id Int @id @default(autoincrement())
email String @unique
city String
version Int
}
function updateOne() {
const user = await prisma.user.findUnique({ id: 1 });

await prisma.user.update({
where: { id: user.id, version: user.version },
data: { city: 'Berlin', version: { increment: 1 } },
});
}

function updateTwo() {
const user = await prisma.user.findUnique({ id: 1 });

await prisma.user.update({
where: { id: user.id, version: user.version },
data: { city: 'New York', version: { increment: 1 } },
});
}

function main() {
await Promise.allSettled([updateOne(), updateTwo()]);
}

权限检查

¥Permission checks

你可以过滤非唯一字段以在更新期间检查权限。

¥You can filter on non-unique fields to check permissions during an update.

在以下示例中,用户想要更新帖子标题。where 语句检查 authorId 中的值以确认用户是帖子的作者。如果用户是帖子作者,则应用仅更新帖子标题。

¥In the following example, a user wants to update a post title. The where statement checks the value in authorId to confirm that the user is the author of the post. The application only updates the post title if the user is the post author.

await prisma.post.update({
where: { id: 1, authorId: 1 },
data: { title: 'Updated post title' },
});

软删除

¥Soft deletes

你可以过滤非唯一字段来处理软删除。

¥You can filter on non-unique fields to handle soft deletes.

在下面的示例中,如果帖子被软删除,我们不想返回该帖子。仅当 isDeleted 中的值为 false 时,该操作才会返回该帖子。

¥In the following example, we do not want to return a post if it is soft-deleted. The operation only returns the post if the value in isDeleted is false.

prisma.Post.findUnique({ where: { id: postId, isDeleted: false } });

UserWhereUniqueInput 注意事项

¥UserWhereUniqueInput considerations

带有 UserWhereUniqueInput 的布尔运算符

¥Boolean operators with UserWhereUniqueInput

对于 UserWhereUniqueInput,你必须在布尔运算符 ANDORNOT 之外至少指定一个唯一字段。你仍然可以将这些布尔运算符与过滤器中的任何其他唯一字段或非唯一字段结合使用。

¥With UserWhereUniqueInput, you must specify at least one unique field outside of the boolean operators AND, OR, NOT. You can still use these boolean operators in conjunction with any other unique fields or non-unique fields in your filter.

在以下示例中,我们结合 email 测试唯一字段 id。这是有效的。

¥In the following example, we test id, a unique field, in conjunction with email. This is valid.

await prisma.user.update({
where: { id: 1, OR: [{ email: "bob@prisma.io" }, { email: "alice@prisma.io" }] },
// ^^^ Valid: the expression specifies a unique field (`id`) outside of any boolean operators
data: { ... }
})

// SQL equivalent:
// WHERE id = 1 AND (email = "bob@prisma.io" OR email = "alice@prisma.io")

以下示例无效,因为在任何布尔运算符之外没有唯一字段:

¥The following example is not valid, because there is no unique field outside of any boolean operators:

await prisma.user.update({
where: { OR: [{ email: "bob@prisma.io" }, { email: "alice@prisma.io" }] },
// ^^^ Invalid: the expressions does not contain a unique field outside of boolean operators
data: { ... }
})

一对一的关系

¥One-to-one relations

从版本 4.5.0 开始,你可以在 一对一的关系 上的以下操作中过滤非唯一字段:

¥From version 4.5.0, you can filter on non-unique fields in the following operations on one-to-one relations:

  • 嵌套更新

    ¥Nested update

  • 嵌套更新插入

    ¥Nested upsert

  • 嵌套断开连接

    ¥Nested disconnect

  • 嵌套删除

    ¥Nested delete

Prisma Client 自动使用唯一的过滤器来选择适当的相关记录。因此,你不需要在 where 语句中使用 WhereUniqueInput 生成类型 指定唯一的过滤器。相反,where 语句具有 WhereInput 生成的类型。你可以用这个来过滤,不受 WhereUniqueInput 的限制。

¥Prisma Client automatically uses a unique filter to select the appropriate related record. As a result, you do not need to specify a unique filter in your where statement with a WhereUniqueInput generated type. Instead, the where statement has a WhereInput generated type. You can use this to filter without the restrictions of WhereUniqueInput.

嵌套更新示例

¥Nested update example

await prisma.user.update({
where: { id: 1, },
data: {
to_one: {
// Before Prisma version 4.5.0
update: { field: "updated" }
// From Prisma version 4.5.0, you can also do the following:
update: { where: { /*WhereInput*/ }, data: { field: "updated" } } }
}
}
})
嵌套更新插入示例

¥Nested upsert example

await prisma.user.update({
where: { id: 1, },
data: {
to_one: {
upsert: {
where: { /* WhereInput */ } // new argument from Prisma 4.5.0
create: { /* CreateInput */ },
update: { /* CreateInput */ },
}
}
}
})
嵌套断开示例

¥Nested disconnect example

await prisma.user.update({
where: { id: 1, },
data: {
to_one: {
// Before Prisma version 4.5.0
disconnect: true
// From Prisma version 4.5.0, you can also do the following:
disconnect: { /* WhereInput */ }
}
}
})
嵌套删除示例

¥Nested delete example

await prisma.user.update({
where: { id: 1, },
data: {
to_one: {
// Before Prisma version 4.5.0
delete: true
// From Prisma version 4.5.0, you can also do the following:
delete: { /* WhereInput */ }
}
}
})

PrismaPromise 行为

¥PrismaPromise behavior

所有 Prisma 客户端查询都会返回 PrismaPromise 的实例。这是 "thenable",意味着 PrismaPromise 仅在你调用 await.then().catch() 时执行。此行为与常规 JavaScript Promise 不同,后者立即开始执行。

¥All Prisma Client queries return an instance of PrismaPromise. This is a "thenable", meaning a PrismaPromise only executes when you call await or .then() or .catch(). This behavior is different from a regular JavaScript Promise, which starts executing immediately.

例如:

¥For example:

const findPostOperation = prisma.post.findMany({}); // Query not yet executed

findPostOperation.then(); // Prisma Client now executes the query
// or
await findPostOperation; // Prisma Client now executes the query

使用 $transaction API 时,此行为使 Prisma 客户端可以将所有查询作为单个事务传递到查询引擎。

¥When using the $transaction API, this behavior makes it possible for Prisma Client to pass all the queries on to the query engine as a single transaction.