// Query public async getProfileName(id: string): Promise<string> { const profileName = await this.prisma.user.findFirst({ where: { id }, select: { name: true, }, }); if (!profileName) { throw new NotFoundError(); } return JSON.stringify(profileName); } // Mutations // create const newUser = await prisma.user.create({ data: { name: "Alice", email: "alice@example.com", }, }); // update const updatedUser = await prisma.user.update({ where: { id: 1 }, data: { name: "Updated Name", }, }); // delete const deletedUser = await prisma.user.delete({ where: { id: 1 }, });
where
(filtering)findMany
findMany
defaults to AND
Below where
clause will return records that match both name
and email
field conditions
where: { name: { in: ['Sam', 'Clemens', 'Bob'], }, email: { contains: 'example.com', }, }
Override the default AND
behavior by using OR[]
field wrapping
where: { OR: [ { name: { in: ['Sam', 'Clemens', 'Bob'], }, }, { email: { contains: 'example.com' }, }, ], }
in
Find values that exist in the list
null
values are not returned
in
and NOT
to return user
whose name
is not in the list, users with null
value names are not returnedExample: Get User
records where the id
can be found in the following list:
[22, 91, 14, 2, 5]
const getUser = await prisma.user.findMany({ where: { id: { in: [22, 91, 14, 2, 5] }, }, });
NOT
Exclude records from the result set using the NOT
field
const getUser = await prisma.user.findMany({ where: { NOT: { name: { in: ['Saqui', 'Clementine', 'Bob'] }, }, }, })
await prisma.$transaction([ prisma.user.create({ data: { name: "Bob" } }), prisma.post.create({ data: { title: "New Post", content: "Content" } }), ]);
Logging Prisma results need Json Stringify
console.log(JSON.stringify(result));
// Define a User model model User { id Int @id @default(autoincrement()) name String email String @unique posts Post[] }
Write your schema updates to the schema file
repo_name/prisma/schema.prisma
OR Create a new migration file using yarn
yarn workspace workspace_name db:makeMigration migration_name
This will create a new migration.sql
containing the effective SQL changes based on the schema delta generated
Running yarn db:migrate
will apply the new changes to your local database
$queryRaw
Accepts template literal string to execute as a SQL query
const result = await prisma.$queryRaw`SELECT * FROM User`
Because it accepts a template literal string, you can pass variables to the query
const email = 'emelie@prisma.io'; const result = await prisma.$queryRaw`SELECT * FROM User WHERE email = ${email}`;