Reputation: 735
Hasura: How to establish relationship to existing record (many to many) at insert time?
I have two tables: product and category that are linked to each other in a many to many relationship based on an id column in each table and an intermediary table product_category.
I can insert records directly into postgres for both tables and link them with product_category and this works great in Hasura for queries so I know I have set things up properly.
What I want to be able to do is insert a new product and knowing the id of a category (or categories) I want to establish the relationship at insert time. Preferably without a seperate call
The documentation only covers inserting both the object and related objects at the same time but what if the other one already exists?
I have tried what I would expect to work (linking this product to category with id 1):
mutation MyMutation {
insert_product_one(
object: {
name: "Champion",
category: {data: {id: 1}}
}) {
id
}
}
But that throws:
"Not-NULL violation. null value in column \"product_id\" violates not-null constraint"
How can I insert this new product and link it to one or more categories? Preferably all in one statement but even an example of retrieving the generated id and an update mutation would be not ideal, but non-the-less a solution.
Update: As a sanity check I've recreated the product and category tables as a minimal, basic example and tried both my query and the upsert conflict method xadm suggested.
The data and relations I've added some screenshots of here:
https://i.sstatic.net/HaVrh.jpg
mutation MyMutation {
insert_testproduct_one(
object: {
name: "Champion",
category: {
data: {id: 1},
on_conflict: { constraint: primarykeything , update_columns: [id] }
}
}) {
id
}
}
The error is similar: "Not-NULL violation. null value in column \"testcategory_id\" violates not-null constraint"
Note: primarykeything is the primary key on the bridge table consisting of the two ids.
Upvotes: 3
Views: 2086
Reputation: 1946
Since it's a many to many relationship, you have a join table in between them. From what I can see in the screenshot you posted the id for the category in your category relationship is called testcategory_id
and not id
.
mutation MyMutation {
insert_testproduct_one(
object: {
name: "Champion",
category: {
data: {testcategory_id: 1}
}
}) {
id
}
}
For it to work the id in the table testproduct_testcategory has to be auto-incremented
Upvotes: 1