prisma-client-js icon indicating copy to clipboard operation
prisma-client-js copied to clipboard

Is it possible to establish many connections with a single prisma-client-js operation?

Open miyi opened this issue 6 years ago • 4 comments

suppose a post can have many authors and there are currently unauthored posts in the database. Is it possible to connect multiple authors to the same post in a single operation?

t.field('assignAuthorsToPost', {
      type: 'Listing',
      args: {
        postId: idArg(),
        authorIds: idArg({ list: true })
      },
      resolve: (_, { postId, authorIds }, ctx) => {
        return ctx.prisma.listings.update({
          where: {
            id: postId
          },
          data: {
            authors: {
              connect: { id: authorIds }
            }
          }
        })
      }
    })

obviously this isn't going to work, but is there a solution for the type of action I'm trying to do?

miyi avatar Jan 27 '20 23:01 miyi

t.field('assignAuthorsToPost', {
      type: 'Listing',
      args: {
        postId: idArg(),
        authorIds: idArg({ list: true })
      },
      resolve: (_, { postId, authorIds }, ctx) => {
        return ctx.prisma.listings.update({
          where: {
            id: postId
          },
          data: {
            authors: {
              connect: {
                 id: authorIds
              }
            }
          }
        })
      }
    })

found the solution from an example in nexus-prisma

mutation connectRelation {
  createOneUser(
    data: { email: "[email protected]", posts: { connect: [1643] } }
  ) {
    id
  }
}

but so far it's not working for me

miyi avatar Jan 27 '20 23:01 miyi

Have you tried using set instead of connect?

malekjaroslav avatar Jan 29 '20 04:01 malekjaroslav

You can pass an array to connect:

return ctx.prisma.listings.update({
          where: {
            id: postId
          },
          data: {
            authors: {
              connect: [{ id: authorId1 }, {id: authorId2}]
            }
          }
        })

If you have authorIds as an array, map them like so:

return ctx.prisma.listings.update({
          where: {
            id: postId
          },
          data: {
            authors: {
              connect: authorIds.map(id => ({ id }))
            }
          }
        })

Let me know if this addresses your concern.

pantharshit00 avatar Jan 29 '20 18:01 pantharshit00

perfect, thanks

miyi avatar Jan 29 '20 23:01 miyi