Search code examples
sqlmany-to-manyprisma

How to create or update many-to-many relation in Prisma?


I have the following models, and many-to-many relation between them:

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  followings    Artist[]
}

model Artist {
  id           String @id @default(cuid())
  name         String @unique
  spotifyId    String @unique
  followers    User[]
}

When a user logs into my app, I retrieve their current followed artists, and need to update my database.

I have managed to select artists data from database (for updating user <-> artist relation), sample data:

const followings = [
  {
    id: '...',
    name: 'MARINA',
    spotifyId: '6CwfuxIqcltXDGjfZsMd9A'
  },
  {
    id: '...',
    name: 'Dua Lipa',
    spotifyId: '6M2wZ9GZgrQXHCFfjv46we'
  },
]

Now, this is my user object:

const user = {
  id: 'someId',
  name: 'someName',
  email: 'someEmail'
}

I tried to insert or update user <-> artist relation with this query but I'm getting Bad Request error:

await prisma.user.upsert({
    where: {
        email: user.email
    },
    create: {
        name: user.name,
        email: user.email,
        followings: {
            connectOrCreate: followings
        }
    },
    update: {
        followings: {
            connectOrCreate: followings
        }
    }
})

Please advise what I need to do. Thanks in advance.

P.S. I took the idea of the query from Updating a many-to-many relationship in Prisma post, but it didn't work for me, so please don't mark duplicate.


Solution

  • connectOrCreate should specify where key with id (so Prisma could find this entity) and create key with all required model fields (so Prisma could create it if it not already present), but you just passing an array of models. Change your code to this one:

      await prisma.user.upsert({
        where: {
          email: 'user.email',
        },
        create: {
          name: 'user.name',
          email: 'user.email',
          followings: {
            connectOrCreate: [
              {
                create: {
                  name: 'MARINA',
                  spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
                },
                where: { id: '...' },
              },
            ],
          },
        },
        update: {
          followings: {
            connectOrCreate: [
              {
                create: {
                  name: 'MARINA',
                  spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
                },
                where: { id: '...' },
              },
            ],
          },
        },
      });