How to do bi-directional one to one relationship?
See original GitHub issue** Which Category is your question related to? ** graphql-transformer
** What AWS Services are you utilizing? ** AppSync / Dynamo
** Provide additional details e.g. code snippets **
Iām currently running into a situation where initially I had a model like follows:
type Post @model {
id: ID!
title: String!
}
type Response @model {
id: ID!
content: String!
post: Post @connection
}
This correctly stores a āresponsePostIdā for each row in the Response table.
And then I decided I wanted access to āresponseā from the Post model so I modified the schema to the following:
type Post @model {
id: ID!
title: String!
response: Response @connection(name: "PostResponse")
}
type Response @model {
id: ID!
content: String!
post: Post @connection(name: "PostResponse")
}
What this does is create a āpostResponseIdā attribute for every new model in the Posts table and uses $context.source.postResponseId to get Post.response. However I donāt need that index, because to get the response for a post (through the Post.response resolver) I should just use $context.source.id and as the value for "responsePostIdā in the Response data source.
Note if I change the Post schema to a one to many relationship:
type Post @model {
id: ID!
title: String!
responses: [Response] @connection(name: "PostResponse")
}
The Post.responses resolver correctly queries using $context.source.id rather than a $context.source.postResponseId.
I read https://aws-amplify.github.io/docs/cli/graphql?sdk=js and it talks about how to do bidirectional one-to-many relationship and a simple one-to-one relationship but there is no example in there for a bidirectional one-to-one. Am I missing something here. Maybe one-to-one bidirectional relationships are not supported because there is no way to enforce the strict 1:1ness in the database?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:21
- Comments:25 (4 by maintainers)
Hi @ykethan, following up on this, I can see how the
@hasOne
relationship on type A results in a reference to a related model, B, and how the@belongsTo
sets up a relationship back to A.However, I donāt see how to enforce the bi-directional relationship in the sense that creating type A, with a reference to a new type B doesnāt seem to result in the relationship from B to A getting created. As far as I can tell, I need to ensure I update the appropriate field in B to point back to A? If so, is this something I should be able to do with a
BatchPutItem
that creates both A and B at the same time, with references to each other?Any ideas? š or Do we wait for amplify maintainers??