Next.js with Prisma
Install Prisma
npm init -y
npm install prisma -D
Run prisma init
npx prisma init
Set the connection string in the file named .env
DATABASE_URL="mysql://username:password@localhost:3306/dbname"
Update the prisma/prisma.schema
file
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String @db.VarChar(255)
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
model Profile {
id Int @id @default(autoincrement())
bio String?
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
profile Profile?
}
Use migrate
command to create a migration
npx prisma migrate dev --name init
Or, prisma db push
npx prisma db push
NOTE: This should only be used on the localhost / dev
Introspection
npx prisma db pull
Prisma client
npm install @prisma/client
npx prisma generate
index.js
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}