Is there a way to create or connect a relationship...
# orm-help
k
Is there a way to create or connect a relationship in a single mutation? Example: with a
type Product { name: String!, category: [ProductCategory!]! }
and
type ProductCategory { name: String! @unique }
I’d like to do
mutation { createProduct( data: { name: "New product", category: { createOrConnect: { name: "Category A" } } }) }
and make sure the same mutation works when creating “New Product 2” without checking if “Category A” exists. I’ve tried defining both create and connect but that doesn’t work. Thanks!
n
This doesn't exist in the Prisma API, there is an
upsert
operation though which does the same thing without a relation. Note that the code snippet you showed also can not work:
Copy code
mutation {
  createProduct(
    data: {
      name: "New product"
      category: { createOrConnect: { name: "Category A" } }
    }
  )
}
In order to
connect
, you'd need to provide a
unique
property as well (e.g.
id
).
Please open a feature request if you'd like to see this functionality in a future version of Prisma 🙂 https://github.com/prisma/prisma/issues/new?template=feature_request.md
k
In
ProductCategory
type
name
is unique so this would theoretically work.
👍 1
Cool, thanks. I’ve tried
upsert
but as you mentioned it doesn’t create the relation. I’ll open a feature request on Github 🙂.
c
I was looking for something similar for making a seeder. Post the link to the FR when you’ve made it and I’ll give it a thumbs up!
k
I actually found this feature request https://github.com/prisma/prisma/issues/2194 which looks very similar
mavilein commented 27 days ago
We implemented this a few weeks ago. Closing therefore.
So is that feature in the API @nikolasburk or it’s a different one? I don’t see
upsert
in the mutation arguments like described in the docs: https://www.prisma.io/docs/prisma-graphql-api/reference/mutations-qwe2/#nested-mutations