TheAschr
TheAschr

Reputation: 973

Prisma client query for latest

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
}

Upvotes: 16

Views: 24131

Answers (2)

Yahya Aghdam
Yahya Aghdam

Reputation: 578

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,
})

Upvotes: 4

Ryan
Ryan

Reputation: 6347

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,
          },
        },
      },
    },
  })

Upvotes: 20

Related Questions