Prisma client query for latest
Asked Answered
S

2

15

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
}

Silas answered 29/8, 2020 at 22:25 Comment(0)
O
20

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,
          },
        },
      },
    },
  })
Orthogenetic answered 31/8, 2020 at 8:4 Comment(1)
Isn't better to use the findFirst prisma method in this case?Amsterdam
G
4

To get last element, you must have id(Int) in your model So, you can call the last element by id. At least because you choose findMany, it will return an array, select first element by adding [0] to the end of code:

const latestQuery = await prisma.modelName.findMany({
        orderBy: {
            id: 'desc',
        },
        take: 1,
})

If you dont add where it will return last element without any condition but if you want to add condition line who has name equal "some name" and age to 25 and etc, you can add it in where:

const latestQuery = await prisma.modelName.findMany({
    where:{
        name: "some name",
        age: 25
    },
    orderBy: {
        id: 'desc',
    },
    take: 1,
})
Goggler answered 24/3, 2023 at 22:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.