title: Hasura: How to establish relationship to existing record (many to many) at insert time?
body: <p>Hasura: How to establish relationship to existing record (many to many) at insert time?</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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</p>
  
  <p><a href="https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships" rel="nofollow noreferrer">https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships</a></p>
  
  <p>The documentation only covers inserting both the object and related objects at the same time but what if the other one already exists?</p>
  
  <p>I have tried what I would expect to work (linking this product to category with id 1):</p>
  
  <pre><code>mutation MyMutation {
    insert_product_one(
      object: {
        name: "Champion", 
        category: {data: {id: 1}}
      }) {
      id
    }
  }
  </code></pre>
  
  <p>But that throws:</p>
  
  <p>"Not-NULL violation. null value in column \"product_id\" violates not-null constraint"</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>The data and relations I've added some screenshots of here:</p>
  
  <p><a href="https://imgur.com/a/GUomMbe" rel="nofollow noreferrer">https://imgur.com/a/GUomMbe</a></p>
  
  <pre><code>mutation MyMutation {
    insert_testproduct_one(
      object: {
        name: "Champion", 
        category: {
            data: {id: 1},
            on_conflict: { constraint: primarykeything , update_columns: [id] }
      }
      }) {
      id
    }
  }
  </code></pre>
  
  <p>The error is similar: "Not-NULL violation. null value in column \"testcategory_id\" violates not-null constraint"</p>
  
  <p>Note: primarykeything is the primary key on the bridge table consisting of the two ids.</p>