DEV Community

Goran Jakovljevic
Goran Jakovljevic

Posted on

Prisma ORM update explicit many to many relations

I was struggling to find this in docs. So, when you have explicit many to many relationship, lets say you have post that has multiple tags. And you want to edit that post and pass up new tags or edit/remove existing ones. This is the way to do it:

const response: jobs = await prisma.posts.update({
            data: {
                ...data,
                users: { connect: { id: session.user.id } },
                posts_tags: {
                    deleteMany: {},
                    create: tags.map((tag) => ({
                        tags: { connect: { id: tag } },
                    })),
                },
            },
            where: {
                slug: postSlug,
            },
        });
Enter fullscreen mode Exit fullscreen mode

So first you pass up deleteMany: {}, which will delete all connections between post and tags. Then you are assigning/connecting new ones.

Top comments (5)

Collapse
 
yash49 profile image
Yash Shah

I also did the same thing, If someone finds a better approach then please provide it by comment.

Collapse
 
leanfj profile image
Leandro Ferreira de Jesus

Tnaks a lot bro!

Collapse
 
gdevtech profile image
Jesus Guzman

Here is what worked for me

return await ctx.prisma.product.update({
        where: {
          id: input.id,
        },
        data: {
          categories: {
            create: [
              {
                category: {
                  create: {
                    name: input.name,
                  },
                },
              },
            ],
          },
        },
      });
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kimdevgit profile image
Kim Dev

Thank youuuuuu, i struggle with this for several hours 😭

Collapse
 
njaume profile image
njaume

js doesnt guarantee the insertion order of the keys, so it might not work, right ?