SELECT * FROM posts
prisma.post.findMany()
SELECT * FROM posts WHERE id = 1
prisma.post.findUnique({ where: { id: 1 } })
pnpm i prisma --save-dev
pnpm i @prisma/client
pnpm prisma init
// prisma/schema.prisma
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Post {
id Int @id @default(autoincrement())
title String
content String
date DateTime
tags Tag[] @relation("PostTags")
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts Post[] @relation("PostTags")
}
pnpm prisma db push
pnpm prisma generate
DATABASE_URL=./data.db
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function getPost(postId: number) {
const post = await prisma.post.findUnique({
where: { id: postId },
include: { tags: true },
});
return post;
}
// Test it
getPost(1).then(console.log);
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function getTechPosts() {
const posts = await prisma.post.findMany({
where: {
tags: { some: { name: "tech" } },
date: { gte: new Date("2025-01-01") },
},
include: { tags: true },
});
return posts;
}
// Test it
getTechPosts().then(console.log);
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function addPost(title: string, content: string, tagNames: string[]) {
const post = await prisma.post.create({
data: {
title,
content,
date: new Date(),
tags: { connect: tagNames.map(name => ({ name })) },
},
});
return post;
}
// Test it
addPost("My Tech Post", "Cool stuff!", ["tech", "news"]);
pnpm prisma studio