Enfield Li
Enfield Li

Reputation: 2530

How to specify cursor pagination using timestamp in Prisma?

I want to use createdAt as cursor, but prisma's type only allow id field:

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:

  export type postWhereUniqueInput = {
    id?: number
  }

Here's the data 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? Thank you so much for the reply!

Upvotes: 1

Views: 1631

Answers (1)

Enfield Li
Enfield Li

Reputation: 2530

Solution

By adding @unique() attribute:

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

Then I can use cursor createdAt:

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

Upvotes: 3

Related Questions