Database Integration with PrismaLesson 4.3
How to perform CRUD operations with Prisma in Next.js
findMany, findUnique, create, update, delete, where, select, include, orderBy, take, skip, upsert
Reading Data
import { prisma } from '@/lib/prisma'
// All posts, newest first, with author name
const posts = await prisma.post.findMany({
where: { published: true },
include: { author: { select: { name: true } } },
orderBy: { createdAt: 'desc' },
take: 10,
skip: 0,
})
// Single post by ID
const post = await prisma.post.findUnique({
where: { id: postId },
})Writing Data
// Create
const newPost = await prisma.post.create({
data: {
title: 'Hello World',
content: 'My first post',
author: { connect: { id: userId } },
},
})
// Update
await prisma.post.update({
where: { id: postId },
data: { published: true },
})
// Delete
await prisma.post.delete({ where: { id: postId } })
// Upsert (create or update)
await prisma.user.upsert({
where: { email: 'user@example.com' },
update: { name: 'Updated Name' },
create: { email: 'user@example.com', name: 'New User' },
})Use include to JOIN related records and get them back in the result. Use select to return only specific fields — this reduces the data transfer and keeps your types tight. Never use include and select at the same level — pick one.
