Nested Writes
Check out the code for the note we're creating:
await prisma.note.create({
data: {
id: 'd27a197e',
title: 'Basic Koala Facts',
content:
'Koalas are found in the eucalyptus forests of eastern Australia. They have grey fur with a cream-coloured chest, and strong, clawed feet, perfect for living in the branches of trees!',
ownerId: kody.id,
images: {
create: [
{
altText: 'an adorable koala cartoon illustration',
contentType: 'image/png',
blob: await fs.promises.readFile(
'./tests/fixtures/images/kody-notes/cute-koala.png',
),
},
{
altText: 'a cartoon illustration of a koala in a tree eating',
contentType: 'image/png',
blob: await fs.promises.readFile(
'./tests/fixtures/images/kody-notes/koala-eating.png',
),
},
],
},
},
})
Notice that we're actually creating two images while we create the note? This is
called a nested query.
This generates more optimal SQL queries than running multiple queries.
And it also manages connecting the foreign keys for us. Without using nested
queries, we have to do that ourselves, which is why we have to update our note
after creating the image:
await prisma.note.update({
where: { id: firstNote.id },
data: {
images: {
connect: [{ id: newImage1.id }, { id: newImage2.id }],
},
},
})
Instead, I want you to nest everything into a single query. It will get a little
nested, and you may feel it's better to break it up into multiple queries.
Luckily that's your prerogative in your own app, but I want you to try it out
first. As mentioned, there are legitimate benefits to nesting these queries.
Also, we'll make it better in the next exercise.
You may find the docs links below to be useful here.
Once you're finished, seed the database again to check your work:
npx prisma db seed