排序
可以在任何字段上执行排序,但建议仅按索引字段排序以提高性能。
排序是使用字段模块的 order
函数定义的,该函数接受一个 prisma_client_rust::Direction
。它可以在 find_first
和 find_many
查询上执行,也可以链接到 fetch
调用以获取许多关联,其方式类似于 关联分页。
示例使用以下模式
generator client {
provider = "cargo prisma"
output = "src/prisma.rs"
}
model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean
title String
content String?
desc String?
comments Comment[]
}
model Comment {
id String @id @default(cuid())
createdAt DateTime @default(now())
content String
post Post @relation(fields: [postID], references: [id])
postID String
}
索引字段
以下示例将按 id
从低到高对 posts
进行排序
use prisma::post;
use prisma_client_rust::Direction;
let posts: Vec<post::Data> = client
.post()
.find_many(vec![])
.order_by(post::id::order(Direction::Asc))
.exec()
.await
.unwrap();
非索引字段
以下示例将按 created_at
对 posts
进行排序,即使它不是索引字段。
use prisma::post;
use prisma_client_rust::Direction;
let posts: Vec<post::Data> = client
.post()
.find_many(vec![])
.order_by(post::created_at::order(Direction::Asc))
.exec()
.await
.unwrap();
与分页结合
以下示例将对所有 post
记录进行排序,然后分页选择其中一部分。
use prisma::post;
use prisma_client_rust::Direction;
let posts: Vec<post::Data> = client
.post()
.find_many()
.order_by(post::created_at::order(Direction::Desc))
.cursor(post::id::equals("abc".to_string()))
.take(5)
.exec()
.await
.unwrap();