简体   繁体   中英

GraphQL: Querying for a value from another table from a mutation

Let's say I have a table t1 that is foreign key'd to another table t2 . For simplicity, t2 only has columns 'name' and 'id' which are both unique. I store the id in t1 .

My problem is I want to write a mutation where I know the name but I don't know the id when I go to store something in t1 . Is there a way to query inside of my mutation so that it converts the value in my statement?

Perhaps a plugin I can add to my project?

I end up with something like this where I pass in a known name but I want to store the id

mutation addT1(
  $knownT2Name: String!,
) {
  createT1 (
    input: {
      t1: {
        id: $component
        # Is there a way to convert this to the id inside the query
        # Or do I need to query for the id with the name first then pass that in?
        t2_id: $knownT2Name
      }
    }
  ) {
    t1 {
      id
      t2_id
    }
  }
}

This is a simple example. The reason I don't want to query for the id with the name is in actuality t1 is foreign key'd to a myriad of other tables with the same situation and I don't want to do 9+ queries just to convert each string to an integer id.

I would much rather be able to do something like this:

mutation addT1(
  $knownT2Name: String!,
) {
  createT1 (
    input: {
      t1: {
        id: $component
        t2_id: t2Byt2(name: $knownT2Name) { id }
      }
    }
  ) {
    t1 {
      id
      t2_id
    }
  }
}

Where t2Byt2(name: $knownT2Name) { id } would be a sub-query that passes the name and gets the id, then stores the id in 't2_id'

I'm looking at a nested mutations plugin for postgraphile ( Here's the GitHub )but I haven't had any traction. It's not quite what I'm looking for.

For the simple relationship I believe you want something like: (using the nested mutations plugin). This only works on CREATE. No luck with an UPSERT.

mutation addT1($t1Name: String!, $t2Name: String!) {
  createT1(
    input: { 
      T1: { 
        name: $t1Name, 
        t2ToT2: { connectByT2: { name: $t2Name } }
      }
    }
  ) {
    t1 {
      t1Id
      name
      t2ByT2 {
        name
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM