查询过滤器
示例使用以下 Prisma 架构
model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean
title String
content String?
views Int @default(0)
comments Comment[]
}
model Comment {
id String @id @default(cuid())
createdAt DateTime @default(now())
content String
post Post @relation(fields: [postID], references: [id])
postID String
}
类型过滤器
您可能希望构建详细的查询,例如数据库列是否包含某个单词,或者某个数字是否大于或小于某个值。在本页中,您可以按类型浏览可用的过滤器方法。所有这些查询都是完全类型安全的,并且独立于底层数据库。
字符串过滤器
// query for posts where the title is "my post"
db.Post.Title.Equals("my post"),
// query for titles containing the string "post"
db.Post.Title.Contains("post"),
// query for titles starting with "my"
db.Post.Title.StartsWith("my"),
// query for titles ending with "post"
db.Post.Title.EndsWith("post"),
数字过滤器
// query for all posts which have exactly 50 views
db.Post.Views.Equals(50),
// query for all posts which have less than or exactly 50 views
db.Post.Views.Lte(50),
// query for all posts which have less than 50 views
db.Post.Views.Lt(50),
// query for all posts which have more than or exactly 50 views
db.Post.Views.Gte(50),
// query for all posts which have more than 50 views
db.Post.Views.Gt(50),
时间过滤器
// query for all posts which equal an exact date
db.Post.CreatedAt.Equals(yesterday),
// query for all posts which were created in the last 6 hours(createdAt > 6 hours ago)
db.Post.CreatedAt.Gt(time.Now().Add(-6 * time.Hour)),
// query for all posts which were created in the last 6 hours(createdAt >= 6 hours ago)
db.Post.CreatedAt.Gte(time.Now().Add(-6 * time.Hour)),
// query for all posts which were created until yesterday
db.Post.CreatedAt.Lt(time.Now().Truncate(24 * time.Hour)),
// query for all posts which were created until yesterday including today's 00:00:00
db.Post.CreatedAt.Lte(time.Now().Truncate(24 * time.Hour)),
可选类型过滤器
可选字段在 Go 中很难表示,因为 SQL 有 NULL,但 Go 没有可空类型。通常,社区默认使用指针,但在所有地方提供指针可能很麻烦。为了使用指针设置 NULL,您可以使用 XOptional
方法变体。
// set an optional field with a specific string
db.Post.Content.Equals("my description")
// set an optional field by using a pointer, where a nil pointer means
// to set NULL in the database
db.Post.Content.EqualsOptional(nil)
// or by using a pointer
content := "string"
// ...
db.Post.Content.EqualsOptional(&content)
通用
您可以应用一些通用过滤器。请注意,模型必须用于保留类型信息。
不
如果你想否定一个查询,可以使用 Not
。
以下查询查询所有标题不等于“123”的帖子
db.Post.Not(
db.Post.Title.Equals("123"),
)
或
你可以使用 Or
。
以下查询查询所有标题等于“123”或内容等于“456”的帖子
db.Post.Or(
db.Post.Title.Equals("123"),
db.Post.Content.Equals("456"),
)