Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Jul 1, 2024

Relational models

API (GraphQL) has the capability to handle relationships between Models, such as has one, has many, and belongs to. In Amplify GraphQL APIs, this is done with the @hasOne, @hasMany and @belongsTo directives as defined in the GraphQL data modeling documentation.

By default, GraphQL APIs requests generate a selection set with a depth of 0. Connected relationship models are not returned in the initial request, but can be lazily loaded as needed with an additional API request. We provide mechanisms to customize the selection set, which allows connected relationships to be eagerly loaded on the initial request.

With versions of Amplify CLI @aws-amplify/cli@12.12.2 and API Category @aws-amplify/amplify-category-api@5.11.5, an improvement was made to how relational field data is handled in subscriptions when different authorization rules apply to related models in a schema. The improvement redacts the values for the relational fields, displaying them as null or empty, to prevent unauthorized access to relational data.

This redaction occurs whenever it cannot be determined that the child model will be protected by the same permissions as the parent model.

Because subscriptions are tied to mutations and the selection set provided in the result of a mutation is then passed through to the subscription, relational fields in the result of mutations must be redacted.

If an authorized end-user needs access to the redacted relational fields, they should perform a query to read the relational data.

Additionally, subscriptions will inherit related authorization when relational fields are set as required. To better protect relational data, consider modifying the schema to use optional relational fields.

  • Lazy and Eager Loading: Lazy and eager loading relationships is no longer supported for Mutations and Subscriptions. However, you can continue to perform eager or lazy loading for Queries.

  • Subscriptions and Related Models: When performing a subscription and you need to retrieve the related model, perform a lazy or eager loaded query using the model identifier from the subscription event to continue to retrieve the related data.

Based on the security posture of your application, you can choose to revert to the subscription behavior before this improvement was made. To do so, use the subscriptionsInheritPrimaryAuth feature flag under graphqltransformer in the amplify/backend/cli.json file.

  • If enabled, subscriptions will inherit the primary model authorization rules for the relational fields.
  • If disabled, relational fields will be redacted in mutation response when there is a difference between auth rules between primary and related models.

Prerequisites

The following examples have a minimum version requirement of the following:

  • Amplify CLI v12.7.0
  • Amplify Android Library v2.14.0
  • This guide uses updated model types generated by the Amplify CLI. To follow this guide, locate "generatemodelsforlazyloadandcustomselectionset" in {project-directory}/amplify/cli.json and set the value to true.

If you already have relational models in your project, you must re-run amplify codegen models after updating the feature flag. After the models have been updated, breaking changes will need to be addressed because relationship fields will now be wrapped in ModelList/ModelReference types. Follow the rest of the guide on this page information on how to use the new lazy supported models.

Create a GraphQL schema with relationships between models

For the following example, let's add a Post and Comment model to the schema:

type Post @model {
id: ID!
title: String!
rating: Int!
comments: [Comment] @hasMany
}
type Comment @model {
id: ID!
content: String
post: Post @belongsTo
}

Generate the models for the updated schema using the Amplify CLI.

amplify codegen models

Creating relationships

In order to create connected models, you will create an instance of the model you wish to connect and pass it to Amplify.API.mutate:

Post post = Post.builder()
.title("My Post with comments")
.rating(10)
.build();
Comment comment = Comment.builder()
.post(post) // Directly pass in the post instance
.content("Loving Amplify API!")
.build();
Amplify.API.mutate(ModelMutation.create(post),
savedPost -> {
Log.i("MyAmplifyApp", "Post created.");
Amplify.API.mutate(ModelMutation.create(comment),
savedComment -> Log.i("MyAmplifyApp", "Comment created."),
failure -> Log.e("MyAmplifyApp", "Comment not created.", failure)
);
},
failure -> Log.e("MyAmplifyApp", "Post not created.", failure)
);
val post = Post.builder()
.title("My Post with comments")
.rating(10)
.build()
val comment = Comment.builder()
.post(post) // Directly pass in the post instance
.content("Loving Amplify API!")
.build()
Amplify.API.mutate(ModelMutation.create(post),
{
Log.i("MyAmplifyApp", "Post created")
Amplify.API.mutate(ModelMutation.create(comment),
{ Log.i("MyAmplifyApp", "Comment created") },
{ Log.e("MyAmplifyApp", "Comment not created", it) }
)
},
{ Log.e("MyAmplifyApp", "Post not created", it) }
)
val post = Post.builder()
.title("My Post with comments")
.rating(10)
.build()
val comment = Comment.builder()
.post(post) // Directly pass in the post instance
.content("Loving Amplify API!")
.build()
try {
Amplify.API.mutate(ModelMutation.create(post))
Log.i("MyAmplifyApp", "Post created.")
Amplify.API.mutate(ModelMutation.create(comment))
Log.i("MyAmplifyApp", "Comment created.")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Create failed", error)
}

Querying relationships

This example demonstrates an initial load of a Post with a subsequent fetch to load a page of comments for the post.

Amplify.API.query(
ModelQuery.get(Post.class, new Post.PostIdentifier("123")),
response -> {
Post post = response.getData();
ModelList<Comment> commentsModelList = post.getComments();
if (commentsModelList instanceof LoadedModelList) {
List<Comment> comments =
((LoadedModelList<Comment>) commentsModelList).getItems();
Log.i("MyAmplifyApp", "Loaded " + comments.size() + " comments.");
} else if (commentsModelList instanceof LazyModelList) {
((LazyModelList<Comment>) commentsModelList).fetchPage(
page -> {
List<Comment> comments = page.getItems();
Log.i("MyAmplifyApp", "Loaded " + comments.size() + " comments.");
},
failure -> Log.e("MyAmplifyApp, ", "Failed to fetch comments", failure)
);
}
},
failure -> Log.e("MyAmplifyApp", "Failed to query post.", failure)
);
Amplify.API.query(
ModelQuery[Post::class.java, Post.PostIdentifier("123")],
{ response ->
val post = response.data
when (val commentsModelList = post.comments) {
is LoadedModelList -> {
val comments = commentsModelList.items
Log.i("MyAmplifyApp", "Loaded ${comments.size} comments")
}
is LazyModelList -> {
commentsModelList.fetchPage(
{ page ->
val comments = page.items
Log.i("MyAmplifyApp", "Fetched ${comments.size} comments")
},
{ Log.e("MyAmplifyApp, ", "Failed to fetch comments", it) }
)
}
}
},
{ Log.e("MyAmplifyApp, ", "Failed to fetch post", it) }
)
try {
val response =
Amplify.API.query(ModelQuery[Post::class.java, Post.PostIdentifier("123")])
val post = response.data
val comments = when (val commentsModelList = post.comments) {
is LoadedModelList -> {
commentsModelList.items
}
is LazyModelList -> {
commentsModelList.fetchPage().items
}
}
Log.i("MyAmplifyApp", "Fetched ${comments.size} comments")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Failed to fetch post and its comments", error)
}

In order to handle the loaded/lazy states of relationships, the code generated models wrap relationships in ModelReference and ModelList types.

public final class Post implements Model {
public ModelList<Comment> getComments()
}
public final class Comment implements Model {
public ModelReference<Post> getPost()
}

ModelReference and ModelList types are either Lazy (Default) or Loaded. See Customizing Query Depth to learn how to eagerly load connected relationships.

  • ModelReference<M>
    • LazyModelReference<M>
    • LoadedModelReference<M>
  • ModelList<M>
    • LazyModelList<M>
    • LoadedModelList<M>

Unwrap ModelReference type

void getPostFromComment(Comment comment) {
ModelReference<Post> postReference = comment.getPost();
if (postReference instanceof LoadedModelReference) {
LoadedModelReference<Post> loadedPost = ((LoadedModelReference<Post>) postReference);
Post post = loadedPost.getValue();
Log.i("MyAmplifyApp", "Post: " + post);
} else if (postReference instanceof LazyModelReference) {
LazyModelReference<Post> lazyPost = ((LazyModelReference<Post>) postReference);
lazyPost.fetchModel(
post -> Log.i("MyAmplifyApp", "Post: $post"),
error -> Log.e("MyAmplifyApp", "Failed to fetch post", error)
);
}
}
fun getPostFromComment(comment: Comment) {
when (val postReference = comment.post) {
is LoadedModelReference -> {
val post = postReference.value
Log.i("MyAmplifyApp", "Post: $post")
}
is LazyModelReference -> {
postReference.fetchModel(
{ post -> Log.i("MyAmplifyApp", "Post: $post") },
{ Log.e("MyAmplifyApp", "Failed to fetch post", it) }
)
}
}
}
suspend fun getPostFromComment(comment: Comment) {
try {
val post = when (val postReference = comment.post) {
is LoadedModelReference -> {
postReference.value
}
is LazyModelReference -> {
postReference.fetchModel()
}
}
Log.i("MyAmplifyApp", "Post: $post")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Failed to fetch post", error)
}
}

Unwrap ModelList type

void getCommentsForPost(Post post) {
ModelList<Comment> commentsModelList = post.getComments();
if (commentsModelList instanceof LoadedModelList) {
LoadedModelList<Comment> loadedComments = ((LoadedModelList<Comment>) commentsModelList);
// Eager loading loads the 1st page only.
loadedComments.getItems();
} else if (commentsModelList instanceof LazyModelList) {
LazyModelList<Comment> lazyComments = ((LazyModelList<Comment>) commentsModelList);
fetchComments(lazyComments, null);
}
}
void fetchComments(LazyModelList<Comment> lazyComments, PaginationToken token) {
lazyComments.fetchPage(
token,
page -> {
List<Comment> comments = page.getItems();
Log.i("MyAmplifyApp", "Page of comments: " + comments);
if (page.getHasNextPage()) {
PaginationToken nextToken = page.getNextToken();
fetchComments(lazyComments, nextToken); // recursively fetch next page
}
},
error -> Log.e("MyAmplifyApp", "Failed to fetch comments page", error)
);
}
// Post comes from server response
fun getCommentsForPost(post: Post) {
when (val commentsModelList = post.comments) {
is LoadedModelList -> {
// Eager loading loads the 1st page only.
commentsModelList.items
}
is LazyModelList -> {
// Helper method to load all pages
fetchComments(commentsModelList)
}
}
}
// Helper method for callback approach
fun fetchComments(lazyComments: LazyModelList<Comment>, token: PaginationToken? = null) {
lazyComments.fetchPage(
token,
{ page ->
val comments = page.items
Log.i("MyAmplifyApp", "Page of comments: $comments")
if (page.hasNextPage) {
val nextToken = page.nextToken
fetchComments(lazyComments, nextToken) // recursively fetch next page
}
},
{ Log.e("MyAmplifyApp", "Failed to fetch comments page", it) }
)
}
suspend fun getCommentsForPost(post: Post) {
try {
val comments = when (val commentsModelList = post.comments) {
is LoadedModelList -> {
// Eager loading loads the 1st page only.
commentsModelList.items
}
is LazyModelList -> {
var page = commentsModelList.fetchPage()
var loadedComments = mutableListOf(page.items) // initial page of comments
// loop through all pages to fetch the full list of comments
while (page.hasNextPage) {
val nextToken = page.nextToken
page = commentsModelList.fetchPage(nextToken)
// add the page of comments to the comments variable
loadedComments += page.items
}
loadedComments
}
}
Log.i("MyAmplifyApp", "Comments: $comments")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Failed to fetch comments", error)
}
}

Deleting relationships

When you delete a parent object in a one-to-many relationship, the children will not be removed. Delete the children before deleting the parent to prevent orphaned data.

// Delete any comments associated with parent post.
Amplify.API.mutate(
ModelMutation.delete(comment),
commentResponse ->
// Once all comments for a post are deleted, the post can be deleted.
Amplify.API.mutate(
ModelMutation.delete(post),
postResponse -> Log.i("MyAmplifyApp", "Deleted comment and post"),
(error) -> Log.e("MyAmplifyApp", "Failed to delete post", error)
),
error -> Log.e("MyAmplifyApp", "Failed to delete comment", error)
);
Amplify.API.mutate(
// Delete any comments associated with parent post.
ModelMutation.delete(comment),
{
// Once all comments for a post are deleted, the post can be deleted.
Amplify.API.mutate(
ModelMutation.delete(post),
{ Log.i("MyAmplifyApp", "Deleted comment and post") },
{ Log.e("MyAmplifyApp", "Failed to delete post", it) }
)
},
{ Log.e("MyAmplifyApp", "Failed to delete comment", it) }
)
try {
// Delete any comments associated with parent post.
Amplify.API.mutate(ModelMutation.delete(comment))
// Once all comments for a post are deleted, the post can be deleted.
Amplify.API.mutate(ModelMutation.delete(post))
Log.i("MyAmplifyApp", "Deleted comment and post")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Failed to delete comment and post", error)
}

Many-to-many relationships

For many-to-many relationships, you can use the @manyToMany directive and specify a relationName. Under the hood, Amplify creates a join table and a one-to-many relationship from both models.

Join table records must be deleted prior to deleting the associated records. For example, for a many-to-many relationship between Posts and Tags, delete the PostTags join record prior to deleting a Post or Tag.

type Post @model {
id: ID!
title: String!
rating: Int
editors: [User] @manyToMany(relationName: "PostEditor")
}
type User @model {
id: ID!
username: String!
posts: [Post] @manyToMany(relationName: "PostEditor")
}
Post post = Post.builder()
.title("My Post")
.rating(10)
.build();
User user = User.builder()
.username("User")
.build();
PostEditor postEditor = PostEditor.builder()
.post(post)
.user(user)
.build();
Amplify.API.mutate(ModelMutation.create(post),
createdPost -> {
Log.i("MyAmplifyApp", "Post created.");
Amplify.API.mutate(ModelMutation.create(user),
createdUser -> {
Log.i("MyAmplifyApp", "User created.");
Amplify.API.mutate(ModelMutation.create(postEditor),
createdPostEditor -> Log.i("MyAmplifyApp", "PostEditor created."),
failure -> Log.e("MyAmplifyApp", "PostEditor not created.", failure)
);
},
failure -> Log.e("MyAmplifyApp", "User not created.", failure)
);
},
failure -> Log.e("MyAmplifyApp", "Post not created.", failure)
);
val post = Post.builder()
.title("My Post")
.rating(10)
.build()
val user = User.builder()
.username("User")
.build()
val postEditor = PostEditor.builder()
.post(post)
.user(user)
.build()
Amplify.API.mutate(ModelMutation.create(post),
{
Log.i("MyAmplifyApp", "Post created")
Amplify.API.mutate(ModelMutation.create(user),
{
Log.i("MyAmplifyApp", "User created")
Amplify.API.mutate(
ModelMutation.create(postEditor),
{ Log.i("MyAmplifyApp", "PostEditor created") },
{ Log.e("MyAmplifyApp", " PostEditor not created", it) }
)
},
{ Log.e("MyAmplifyApp", " User not created", it) }
)
},
{ Log.e("MyAmplifyApp", "Post not created", it) }
)
val post = Post.builder()
.title("My Post")
.rating(10)
.build()
val user = User.builder()
.username("User")
.build()
val postEditor = PostEditor.builder()
.post(post)
.user(user)
.build()
try {
Amplify.API.mutate(ModelMutation.create(post))
Log.i("MyAmplifyApp", "Post created.")
Amplify.API.mutate(ModelMutation.create(user))
Log.i("MyAmplifyApp", "User created.")
Amplify.API.mutate(ModelMutation.create(postEditor))
Log.i("MyAmplifyApp", "PostEditor created.")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Create failed", error)
}

This example illustrates the complexity of working with multiple sequential create operations. To remove the nested callbacks, consider using Amplify's support for Coroutines.

Customizing query depth with custom selection sets

You can perform a nested query through one network request, by specifying which connected models to include. This is achieved by using the optional includes parameter for a GraphQL request.

Query for the Comment and the Post that it belongs to:

Amplify.API.query(
ModelQuery.<Comment, CommentPath>get(
Comment.class,
new Comment.CommentIdentifier("c1"),
(commentPath -> includes(commentPath.getPost()))
),
response -> {
Comment comment = response.getData();
ModelReference<Post> postReference = comment.getPost();
if (postReference instanceof LoadedModelReference) {
Post post = ((LoadedModelReference<Post>) postReference).getValue();
Log.i("MyAmplifyApp", "Post: " + post);
}
},
failure -> Log.e("MyAmplifyApp", "Failed to fetch post", failure)
);

This will populate the selection set of the post in the GraphQL document which indicates to your GraphQL service to retrieve the post model as part of the operation. Once the comment is loaded, the post model is immediately available in-memory without requiring an additional network request.

Amplify.API.query(
ModelQuery.get<Comment, CommentPath>(
Comment::class.java,
Comment.CommentIdentifier("c1")
) { commentPath ->
includes(commentPath.post)
},
{ response ->
val comment = response.data
val post = (comment.post as? LoadedModelReference)?.value
Log.i("MyAmplifyApp", "Post: $post")
},
{ Log.e("MyAmplifyApp", "Failed to fetch post", it) }
)

This will populate the selection set of the post in the GraphQL document which indicates to your GraphQL service to retrieve the post model as part of the operation. Once the comment is loaded, the post model is immediately available in-memory without requiring an additional network request.

try {
val comment = Amplify.API.query(
ModelQuery.get<Comment, CommentPath>(
Comment::class.java,
Comment.CommentIdentifier("c1")
) { commentPath ->
includes(commentPath.post)
}
).data
val post = (comment.post as? LoadedModelReference)?.value
Log.i("MyAmplifyApp", "Post: $post")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Failed to fetch post", error)
}

This will populate the selection set of the post in the GraphQL document which indicates to your GraphQL service to retrieve the post model as part of the operation. Once the comment is loaded, the post model is immediately available in-memory without requiring an additional network request.

Query for the Post and the first page of comments for the post:

Amplify.API.query(
ModelQuery.<Post, PostPath>get(
Post.class,
new Post.PostIdentifier("p1"),
(postPath -> includes(postPath.getComments()))
),
response -> {
Post post = response.getData();
ModelList<Comment> commentsModelList = post.getComments();
if (commentsModelList instanceof LoadedModelList) {
List<Comment> comments = ((LoadedModelList<Comment>) commentsModelList).getItems();
Log.i("MyAmplifyApp", "Comments: " + comments);
}
},
failure -> Log.e("MyAmplifyApp", "Failed to fetch post", failure)
);

The network request for post includes the comments, eagerly loading the first page of comments in a single network call.

Amplify.API.query(
ModelQuery.get<Post, PostPath>(
Post::class.java,
Post.PostIdentifier("p1")
) { postPath ->
includes(postPath.comments)
},
{ response ->
val post = response.data
val comments = (post.comments as? LoadedModelList)?.items
Log.i("MyAmplifyApp", "Comments: $comments")
},
{ Log.e("MyAmplifyApp", "Failed to fetch post", it) }
)

The network request for post includes the comments, eagerly loading the first page of comments in a single network call.

try {
val post = Amplify.API.query(
ModelQuery.get<Post, PostPath>(
Post::class.java,
Post.PostIdentifier("p1")
) { postPath ->
includes(postPath.comments)
}
).data
val comments = (post.comments as? LoadedModelList)?.items
Log.i("MyAmplifyApp", "Comments: $comments")
} catch (error: ApiException) {
Log.e("MyAmplifyApp", "Failed to fetch post", error)
}

The network request for post includes the comments, eagerly loading the first page of comments in a single network call.

You can generate complex nested queries through the includes parameter.

ModelQuery.get<Comment, CommentPath>(Comment::class.java, "c1") { commentPath ->
includes(commentPath.post.comments)
}

This query fetches a comment, eagerly loading the parent post and first page of comments for the post.

ModelQuery.get<Comment, CommentPath>(
Comment::class.java,
"c1"
) { commentPath ->
includes(commentPath.post.comments)
}

This query fetches a comment, eagerly loading the parent post and first page of comments for the post.

ModelQuery.get<PostEditor, PostEditorPath>(PostEditor::class.java, "pe1") { postEditorPath ->
includes(postEditorPath.post, postEditorPath.user)
}

This query fetches a postEditor and eagerly loads its post and user

ModelQuery.get<PostEditor, PostEditorPath>(
PostEditor::class.java,
"pe1"
) { postEditorPath ->
includes(postEditorPath.post, postEditorPath.user)
}

This query fetches a postEditor and eagerly loads its post and user