graphqltypeormtypegraphql

How to describe a schema for many-to-many GraphQl relationships with custom properties?


How to describe a schema for many-to-many GrhapQl relationships with custom properties?

Hi guys! I have the following tables:

+-------------+--------------+----------------------------+
|                        Product                         |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
+-------------+--------------+----------------------------+

+-------------+--------------+----------------------------+
|                        Nutrient                         |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
| unit        | varchar(255) |                            |
| alias       | varchar(255) |                            |
+-------------+--------------+----------------------------+

+-------------+--------------+----------------------------+
|                  Product_To_Nutrient                    |
+-------------+--------------+----------------------------+
| nutrientId  | int(11)      | PRIMARY KEY FOREIGN KEY    |
| productId   | int(11)      | PRIMARY KEY FOREIGN KEY    |
| amount      | int(11)      |                            |
+-------------+--------------+----------------------------+

To get nutrients, I use dataloader.

How can I describe my schema so that I can run the following query and get the AMOUNT for each nutrient? Or maybe I need to rebuild my database, if so, which architecture would be optimal? Thank you in advance for your advice :)

    query Product {
     getProducts {
      id,
      name,
      nutrients: {
       name,
       unit,
       alias,
       AMOUNT
      }
    }

My stack: TypeOrm, TypeGraphQL, MicroOrm, NodeJs.


Solution

  • Querying with GraphQL, you'll have to do through the ingredients

    query Product {
      getProducts {
        id,
        name,
        ingredients: {
          nutrient: {
            id,
            name,
            alias
          },
          quantity,
          unit
        }
      }
    }
    

    To load the ingredient, when querying the products, you can make it an 'eager' relationship.

    Use the Dataloader to load all the nutrients linked to the ingredient.