AWS Amplify Many to many relationship - nested data doesnt work

464 views Asked by At

I am using Amplify and everything worked fine until now. I built a schema where I have a many-to-many relationship and when I get the data with Datastore the result is not what I expected.

Those are my dependencies

https://i.stack.imgur.com/kH5yo.png

My schema looks like this:

type Question @model {
  id: ID!
  name: String!
  answers: [QuestionAnswer] @connection(keyName: "byQuestion", fields: ["id"])
}

type QuestionAnswer
  @model(queries: null)
  @key(name: "byQuestion", fields: ["questionID", "answerID"])
  @key(name: "byAnswer", fields: ["answerID", "questionID"]) {
  id: ID!
  questionID: ID!
  answerID: ID!
  question: Question! @connection(fields: ["questionID"])
  answer: Answer! @connection(fields: ["answerID"])
}

type Answer @model {
  id: ID!
  name: String!
  questions: [QuestionAnswer] @connection(keyName: "byAnswer", fields: ["id"])
}

The depth is currently 5 but I've tried with 10 and I have the same problem.

If I try to query from AppSync like this :

[it works][1]

I get this:

   "data": {
     "syncQuestionAnswers": {
        "items": [
          {
            "question": {
            "name": "How are you?",
            "answers": {
                "items": [
                  {
                    "answer": {
                      "name": "Good"
                    }
                },
                {
                    "answer": {
                      "name": "Bad"
                    }
                }
              ]
            }
          }
        },
        {
          "question": {
             "name": "How are you?",
             "answers": {
               "items": [
                  {
                    "answer": {
                      "name": "Good"
                    }
                  },
                  {
                    "answer": {
                      "name": "Bad"
                    }
                  }
                ]
              }
            }
          }
        ]
      }
    }

The question will appear 2 times, because I have 2 answers assigned to it.

However when I use Datastore on the QuestionAnswer model:

async getQuestions() {
  this.questions = await DataStore.query(QuestionAnswer);
  console.log(this.questions);
}

I get this:

https://i.stack.imgur.com/mijQB.png

Not exactly what I wanted.

What I would like to happen when I query the data it would be this:

  "question": {
    "name": "How are you?",
    "answers": {
      "items": [
        {
          "answer": {
            "name": "Good"
          }
        },
        {
          "answer": {
            "name": "Bad"
          }
        }
      ]
    }
  }

If I'm doing something wrong please tell me what because I'm going crazy :)

0

There are 0 answers