client implementation
// 1. create user then profile
const user = await prisma.user.create({ data: {} })
const profile = await prisma.profile.create({
data: {
name: faker.name.firstName,
userId: user.id
}
})
// 2. create a user with a profile
const user = await prisma.user.create({
data: {
profiel: {
create: {
name: faker.name.firstName(),
}
}
},
// we can also add include here, its not only for queries
})
// get user data only
prisma.user.findUnique({
where: { id: user.id },
})
// { id: 1, email: 'test@gmail.com' }
// get user data included profile all props
prisma.user.findUnique({
where: { id: user.id },
include: { profile: true }
})
// { id: 1, email: 'test@gmail.com', profile: { name: 'Sabin', age: 10, gender: 'male' } }
// get only spesfic props in profile
prisma.user.findUnique({
where: { id: user.id },
include: {
profile: {
select: { name: true }
}
}
})
user can have many posts, but post have one author
model User {
id Int @id @default(autoincrement())
email String @unique
posts Post[]
}
model Post {
title String
// it can be @unique, this mean every post should have id of a user
userId Int
user User @relation(fields: [userId], refrences: [id])
}
// create post
const post = await prisma.post.create({
data: {
user: {
connect: {
id: user.id
}
}
}
})
prisma.user.findMany({
include: {
posts: true
}
})
// { id: 1, email: 'test@gmail.com', posts: [{ name: 'Post1' }] }