insert data with relations
// create
const user = await prisma.user.create({
data: {
name: 'abbas',
email: 'abbas@gmail.com'
},
userPrefrences: { // create other row with this
create: {
receiveEmails: true,
categories: { // if not exist to connect create it
connectOrCreate: {
where: { id: 3 },
create: { name: "Big Data" }
}
}
}
},
profile: { // connect created row with this
connect: {}
}
})
const users = await prisma.user.create({
data: {},
// returned result include only what in data, to include others
include: {
userPrefrences: true
},
// another option is select which enable us to exclude also main fields of row, we should use include or select not both
select: {
name: true,
userPrefrences: true,
another_relation: {
spesficFields: true
}
}
})
query methods and filtring
const users = await prisma.user.findMany()
// fields not necessary be unique
const user = await prisma.user.findFirst()
const user = await prisma.user.findFirstOrThrow() // if not found throw error
// find one depend on unique attribute, should use { where }
const user = await prisma.user.findUnique({
where: {
email: 'kitkat@gmail.com',
// we can use age_name in this case coz we did a unique constain on both of them
age_name: {
age: 27,
name: 'kyle'
}
},
})
const user = await prisma.user.findUniqueOrThrow() // if not found throw error
// filter used with any query function
const users = prisma.user.findMany({
where: {
name: 'kyle'
},
distinct: ["name", "age"], // return unique rows depend on these columns
orderBy: {
age: "desc"
},
// offset pagination
take: 2, // how many users we should take
skip: 1, // how many users to skip
// cursor pagination
take: 2,
cursor: { id: '234589' },
// also we can use include or select here
})