Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prisma client query for latest

Tags:

prisma

prisma2

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
}

like image 921
TheAschr Avatar asked Dec 30 '25 11:12

TheAschr


2 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,
          },
        },
      },
    },
  })
like image 60
Ryan Avatar answered Jan 05 '26 03:01

Ryan


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,
})
like image 31
Yahya Aghdam Avatar answered Jan 05 '26 05:01

Yahya Aghdam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!