Prisma client query for latest

Viewed 4977

Given the following schema. How would I query for the latest commit on each repository using the prisma2 client?

model Commit {
  id   String   @default(uuid()) @id
  date DateTime @default(now())
}

model Branch {
  id           String     @default(uuid()) @id
  commit       Commit     @relation(fields: [commitId],references: [id])
  commitId     String
  repository   Repository @relation(fields: [repositoryId],references: [id])
  repositoryId String
}

model Repository {
  id String @default(uuid()) @id
}

1 Answers

I think your schema should look more like this:

model Commit {
  id        String   @default(uuid()) @id
  branch    Branch   @relation(fields: [branchId], references: [id])
  createdAt DateTime @default(now())
  branchId  String
}

model Branch {
  id           String     @default(uuid()) @id
  name         String
  repository   Repository @relation(fields: [repositoryId], references: [id])
  commits      Commit[]
  repositoryId String
}

model Repository {
  id     String   @default(uuid()) @id
  branch Branch[]
}

And you will be able to get the latest commits from all branches in the repository in this manner:

await prisma.repository.findMany({
    select: {
      branch: {
        select: {
          name: true,
          commits: {
            orderBy: {
              createdAt: 'desc',
            },
            take: 1,
          },
        },
      },
    },
  })
Related