简体   繁体   English

如何在 Prisma 中使用时间戳指定 cursor 分页?

[英]How to specify cursor pagination using timestamp in Prisma?

I want to use createdAt as cursor, but prisma's type only allow id field:我想使用 createdAt 作为 cursor,但 prisma 的类型只允许 id 字段:

post.findMany({
      take: 10,
      orderBy: { createdAt: 'desc' },
      cursor: { id }, // Prisma only provide id here
    });

And cursor is refering to the type "postWhereUniqueInput", it only provide id in it:而 cursor 指的是“postWhereUniqueInput”类型,它只在其中提供id

  export type postWhereUniqueInput = {
    id?: number
  }

Here's the data model:这是数据 model:

model post {
  id             Int            @id() @default(autoincrement())
  createdAt      DateTime       @default(now()) @db.Timestamp(6)
  updatedAt      DateTime       @default(now()) @db.Timestamp(6)
  title          String         @db.VarChar
  content        String?        @db.VarChar
  userId         Int  
  viewCount      Int            @default(0)  
  votePoints     Int            @default(0)
  likePoints     Int            @default(0)
  confusedPoints Int            @default(0)
  laughPoints    Int            @default(0)
  user           user           @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction)
  interactions   interactions[]
  comments       comments[]
}

How can I use the timestamp as cursor?如何将时间戳用作 cursor? Thank you so much for the reply!非常感谢你的回复!

Solution解决方案

By adding @unique() attribute:通过添加@unique()属性:

model post {
  id             Int            @id() @default(autoincrement())
  createdAt      DateTime       @unique() @default(now())
  updatedAt      DateTime       @unique() @updatedAt
  ...
}

Then I can use cursor createdAt :然后我可以使用 cursor createdAt

prismaService.post.findMany({
      cursor: cursor ? { createdAt: cursor } : undefined,
      ...
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM