Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo/React mutating two related tables

Say I have two tables, one containing products and the other containing prices.

In Graphql the query might look like this:

option {
    id
    price {
      id
      optionID
      price
      date
    }
    description
}

I present the user with a single form (in React) where they can enter the product detail and price at the same time.

When they submit the form I need to create an entry in the "product" table and then create a related entry in the "price" table.

I'm very new to Graphql, and React for that matter, and am finding it a steep learning curve and have been following an Apollo tutorial and reading docs but so far the solution to this task is remaining a mystery!

Could someone put me out of my misery and give me, or point me in the direction of, the simplest example of handling the mutations necessary for this?

like image 448
Bigus Avatar asked Oct 29 '22 07:10

Bigus


1 Answers

Long story short, that's something that should actually be handled by your server if you want to optimize for as few requests as possible.

Problem: The issue here is that you have a dependency. You need the product to be created first and then with that product's ID, relate that to a new price.

Solution: The best way to implement this on the server is by adding another field to Product in your mutation input that allows you to input the details for Price as well in the same request input. This is called a "nested create" on Scaphold.

For example:

// Mutation
mutation CreateProduct ($input: CreateProductInput!) {
  createProduct(input: $input) {
    changedProduct {
      id
      name
      price {
        id
        amount
      }
    }
  }
}

// Variables
{
  input: {
    name: "My First Product",
    price: {
      amount: 1000
    }
  }
}

Then, on the server, you can parse out the price object in your resolver arguments and create the new price object while creating the product. Meanwhile, you can also relate them in one go on the server as well.

Hope this helps!

like image 104
vince Avatar answered Jan 04 '23 10:01

vince