Many-To-Many
Was charging forth on this amplify graphql annotation stuff, until I noticed this from the documentation:
The @connection directive enables you to specify relationships between @model object types. Currently, this supports one-to-one, one-to-many, and many-to-one relationships. An error is thrown if you try to configure a many-to-many relationship.
Unfortunately my app is many-to-many. So that's a bummer. I am curious, when will many-to-many relationship work?
Also, could you please as advise on how to do this? I presume I can just forego the @connection annotation and then attach my own resolver which will do some kind of many-to-many look up. Will that work? Will I be able to mix the @searchable annotations with this?
You can implement many to many yourself using two 1-M @connections and a joining @model. For example:
type Post @model {
id: ID!
title: String!
editors: [PostEditor] @connection(name: "PostEditors")
}
# Create a join model and disable queries as you don't need them
# and can query through Post.editors and User.posts
type PostEditor @model(queries: null) {
id: ID!
post: Post! @connection(name: "PostEditors")
editor: User! @connection(name: "UserEditors")
}
type User @model {
id: ID!
username: String!
posts: [PostEditor] @connection(name: "UserEditors")
}
You can then create Posts & Users independently and join them in a many-to-many by creating PostEditor objects. In the future we will support many to many out of the box and will manage setting up the join model for you and configuring better names for the mutations that relate objects. In the future we will also support using batch operations to create bi-directional relationships like friendships that may have some qualifying information on the joining model itself.
Looking forward to more support for association features, having to explicitly define the association types in cases like the example (where no additional columns are needed) can grow a bit out of hand and lead to confusions for larger data schemas that have lots of many-to-many associations. Definitely loses some of the readability that's so nice with defining data models via GraphQL SDL.
Ideally the above could be written as:
type Post {
id: ID!
title: String!
editors: [User!]!
}
type User {
id: ID!
username: String!
posts: [Post!]!
}
The Prisma project has support for this and it's real nice to work with. Not sure the comparison is entirely fair tho as AppSync's project focus seems to be more along integrating a variety of data sources while Prisma has been far slower in adopting more sources but is arguably more feature rich at the model declaration level
@ev-dev This is exactly the type of behavior that will be supported in the future. There is a TODO here https://github.com/aws-amplify/amplify-cli/blob/master/packages/graphql-connection-transformer/src/ModelConnectionTransformer.ts#L132 that is waiting to be worked on and will automatically handle hooking up the join table and additional mutations to enable the many to many.
@mikeparisstuff Are you able to elaborate on the details of how many-to-many connections will be modeled in DynamoDB. For example, will it create another GSI or use some form of GSI Overloading? I haven't messed around with amplify-cli in a while, but it seems like creating a GSI for every relationship will hit DynamoDB's limit of five global secondary indexes per table quite fast.
The reason I ask, is that we are evaluating the use of amplify-cli for an upcoming greenfield project. We have been using AWS Appsync and love it 😃 . Keep up the good work 👍
@affablebloke I will write up a more detailed design and post it here soon. I have been looking into both a general adjacency list approach as well overloading GSIs to get around the GSI limit issues but this may need to be made configurable because there are pros/cons to the approaches. Do you have any approaches in mind that I have not mentioned?
Thanks for the kind words! I'm glad to hear you are enjoying the service thus far!
@mikeparisstuff this service has been a god send please keep up the good work
@mikeparisstuff Sounds good 👍. Those are the same strategies that we use at our company.
For future reference, we have new docs on @connection here https://aws-amplify.github.io/docs/js/graphql#connection.
What is the best way to use this relationship in practice? I have my Many to Many relationships setup but it is unclear what the best way is to utilize the join table. Is it just an additional mutation of creating that join model with the previously created models that you want to relate?
@mikeparisstuff It appears to me that a recent update to the CLI has broken this approach. I believe it's recent only because I had one of these setup at one point and it was working. I thought I didn't need it anymore so I removed it. Now I'm going to add it back again and I'm getting the error below.
Cloudformation gives me the following error when attempting to create a similar many-to-many relationship: Only one resolver is allowed per field. (Service: AWSAppSync; Status Code: 400; Error Code: BadRequestException; Request ID: 06480039-0ade-11e9-aca0-3707b99c7ce2
Edit: I re-created my project for another environment and didn't receive this error again.
What is the best way to use this relationship in practice? I have my Many to Many relationships setup but it is unclear what the best way is to utilize the join table. Is it just an additional mutation of creating that join model with the previously created models that you want to relate?
Yes, that's the way it works. You create the model using the mutation with the IDs of the two related items.
Any updates on this? because I'm about to start a new project that needs lots of many-to-many relationships, so I'm wondering what is the correct way to create the schema of if I should wait until this gets delivered
@mikeparisstuff
You can then create Posts & Users independently and join them in a many-to-many by creating PostEditor objects.
Does it mean that if I query a User Posts via the PostEditor intermediate entity, then it will cause multiple reads on DynamoDB? For instance, 20 user posts will lead to 20 reads on the Posts table instead of one if I want to display a Post title for each PostEditor link in my UI. It may consume the DynamoDB throughput inefficiently. Is it recommended to denormalize data from User and Post into PostEditor manually to prevent the mentioned extra data requests? Is it going to be solved somehow in the future?
I'm waiting too for this update. I heavily need many-to-many relationship for my new project and I would prefer to avoid adding models just to create this relationship...
First-class many-to-many support is a definite need for me too!
Here's how I'm currently handling many-to-many. This is for an app that tracks records for students. Each student can have many records (like book reading progress or read an internet resource). Also, one record can apply to many students (such as when two students complete the same reading assignment).
enum Subject {
SCIENCE
MATH
LANGUAGE
SOCIAL_STUDIES
PHYS_ED
HEALTH
ART
MUSIC
RELIGION
FOREIGN_LANGUAGE
}
type Student @model @auth(rules: [{allow: owner}]) {
id: ID!
firstName: String!
lastName: String!
birthdate: AWSDate!
bookMaps: [BookMap]! @connection(name: "StudentBooks")
resourceMaps: [ResourceMap]! @connection(name: "StudentResources")
}
interface Record {
id: ID!
week: String!
subjects: [Subject]
}
type BookMap @model(queries: null) @auth(rules: [{allow: owner}]) {
id: ID!
bookRecord: BookRecord! @connection(name: "BookStudents")
student: Student! @connection(name: "StudentBooks")
}
type BookRecord implements Record @model @auth(rules: [{allow: owner}]) {
id: ID!
week: String!
subjects: [Subject!]!
studentMaps: [BookMap!]! @connection(name: "BookStudents")
title: String!
progressStart: Int!
progressEnd: Int!
}
type ResourceMap @model(queries: null) @auth(rules: [{allow: owner}]) {
id: ID!
resourceRecord: ResourceRecord! @connection(name: "ResourceStudents")
student: Student! @connection(name: "StudentResources")
}
type ResourceRecord implements Record @model @auth(rules: [{allow: owner}]) {
id: ID!
week: String!
subjects: [Subject!]!
studentMaps: [ResourceMap!]! @connection(name: "ResourceStudents")
location: String!
notes: String
}
And here's what full nested queries look like. Not super clean, eh? :)
query {
listStudents {
items {
id
firstName
bookMaps {
items {
bookRecord {
id
title
}
}
}
}
}
listBookRecords {
items {
id
week
title
studentMaps {
items {
student {
firstName
}
}
}
}
}
}
++
So what would be the mutation call if I want to create a new blogpost and also create and attach the associated comments. Or do I have to fire multiple mutation calls to realize this?
+1 on this as well, from the perspective of someone evaluating options, this particular issue presents as a pain point.
In the future we will support many to many out of the box and will manage setting up the join model for you and configuring better names for the mutations that relate objects.
How long until The Future? I'm ready for my flying car but I need many-to-many.
[…] I had one of these setup at one point and it was working. I thought I didn't need it anymore so I removed it. Now I'm going to add it back again and I'm getting the error below. […]
Only one resolver is allowed per field. (Service: AWSAppSync; Status Code: 400; Error Code: BadRequestException; Request ID: 06480039-0ade-11e9-aca0-3707b99c7ce2
This workaround resolved this for me without having to recreate the AppSync API.