0

If I have a schema which looks like below, where a User can have many images, but I don’t have a field on the image to point back to the User. How do I save a new Image and have it connect to the user? I was thinking I would omit the User field on the Image Type because I’ve no reason to query for the user based on the Image ID. But I don’t know how to make that call to save using the generated prisma client.

type User {
  id: ID! @id
  name: String
  images: [Image] @relation(onDelete: CASCADE)
}

type Image{
  id: ID! @id
  createdAt: DateTime! @createdAt
  filename: String!
}

Normally my create calls, which connect the create with another table, look like this (below) but I believe this code would require a user field on my Image type.

context.prisma.createImage({
      filename: "test",
      user: { connect: { id: args.user.id } }
    })

Am I thinking about this correctly? Should you always have bi-directional references between the two tables with a relationship like this?

One of the major benefits of not having a link to the User is that I can then use the Images table for things other than users. Such as products or what not.

Corey Snyder
  • 236
  • 1
  • 3
  • 12

1 Answers1

0

I believe I have figured this out. I removed the User field on the Image type like I set out to do. Now when I go to add images to user, I use the client like so:

await context.prisma.updateUser({
        where: {
          id: 'cjx4wh7412oyc0b42tbhsu6ez',
        },
        data: {
          images: {
            create: {
              postedBy: { connect: { id: userId } },
              filename: result.filename,
              path: result.path,
              mimetype: result.mimetype,
            }
          }
        }
      })
Corey Snyder
  • 236
  • 1
  • 3
  • 12