Created
October 19, 2021 07:48
-
-
Save ruheni/6c1240fa913c91767c69d0dd3f8936ed to your computer and use it in GitHub Desktop.
Prisma `groupBy` dates snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
generator client { | |
provider = "prisma-client-js" | |
} | |
datasource db { | |
provider = "sqlite" | |
url = "file:./dev.db" | |
} | |
model User { | |
id Int @id @default(autoincrement()) | |
email String @unique | |
name String? | |
posts Post[] | |
} | |
model Post { | |
title String | |
content String? | |
id Int @id @default(autoincrement()) | |
published Boolean @default(false) | |
createdAt DateTime @default(now()) | |
author User? @relation(fields: [authorId], references: [id]) | |
authorId Int? | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PrismaClient } from "@prisma/client" | |
const prisma = new PrismaClient() | |
async function main() { | |
try { | |
await prisma.post.groupBy({ | |
by: ['createdAt'], | |
}) | |
// where date is less than or equal to | |
await prisma.post.groupBy({ | |
by: ['createdAt'], | |
where: { | |
createdAt: { | |
lte: '2021-10-19T07:25:40.634Z' | |
} | |
} | |
}) | |
// ascending order | |
await prisma.post.groupBy({ | |
by: ['createdAt'], | |
orderBy: { | |
createdAt: 'asc' // or 'desc' | |
} | |
}) | |
} catch (error) { | |
throw error | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment