35
loading...
This website collects cookies to deliver better user experience
src/index.ts
copy the next example.import { PrismaClient } from "@prisma/client";
async function main() {
const prisma = new PrismaClient();
try {
const newAuthor = await prisma.author.create({
data: {
firstName: "John",
lastName: "Doe",
},
});
console.log({ newAuthor });
} catch (error) {
console.error(error);
throw error;
} finally {
await prisma.$disconnect();
}
}
main();
prisma.[entity].create
you can insert in your db your entities, but let's see this code in action executing the next two scriptnpx prisma db push
yarn dev
{ newAuthor: { id: 1, firstName: 'John', lastName: 'Doe' } }
console.log({ newAuthor });
....
const newPost = await prisma.post.create({
data: {
title: "First Post",
content: "This is the first post",
published: false,
comments: {
create: {
text: "First comment",
author: {
connect: {
id: newAuthor.id,
},
},
},
},
},
include: {
comments: true,
},
});
console.log("newPost", JSON.stringify(newPost, null, 4));
...
npx prisma db push
yarn dev
newPost {
"id": 7,
"title": "First Post",
"content": "This is the first post",
"published": false,
"createAt": "2021-12-18T12:29:20.982Z",
"updatedAt": "2021-12-18T12:29:20.982Z",
"comments": [
{
"id": 7,
"text": "First comment",
"postId": 7,
"authorId": 7
}
]
}
data
field, this field allows you to indicate all the fields related to your entity, in this case the Post Entity. When I say the entity's fields I am referring to the own fields but also to the fields of its related Entities as you did with the Comment Entity in the previous example....
comments: {
create: {
text: "First comment",
author: {
connect: {
id: newAuthor.id,
},
},
},
},
...
connect
, but what is it? The connect field is another command for Prisma. This command indicates to Prisma that the Author's record already exists in the database and it must not create it but it only needs to create the link between the comment record and the author record.connectOrCreate
. This command allows us to check if the relative record exists and in this case Prisma creates the link between the entities, otherwise if it doesn't exist Prisma creates also this new record. To give you an example, here, the author connect command rewrites with the connectOrCreate
.author: {
connectOrCreate: {
create: {
lastName: "Last name",
firstName: "First name",
},
where: {
id: newAuthor.id,
},
},
},
createMany
method that allows you to do a bulk insert inside a collection. It isn't so different from the create
method. I leave you the link to the documentation here.import { Prisma, PrismaClient } from "@prisma/client";
...
const authorCreate: Prisma.AuthorCreateArgs = {
data: {
firstName: "John",
lastName: "Doe",
},
};
const newAuthor = await prisma.author.create(authorCreate);
...
prisma.schema
file and it doesn't just make this, but we will go deep into this in the next articles.