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 v10.8.0
  • Amplify Library for Swift v2.4.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 some relationships have changed to async. 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:

do {
let post = Post(title: "My post with comments",
rating: 10)
let comment = Comment(content: "Loving Amplify API!",
post: post) // Directly pass in the post instance
let createPostResult = try await Amplify.API.mutate(request: .create(post))
guard case .success = createPostResult else {
print("API response: \(createPostResult)")
return
}
print("Post created.")
let createCommentResult = try await Amplify.API.mutate(request: .create(comment))
guard case .success = createCommentResult else {
print("API response: \(createCommentResult)")
return
}
print("Comment created.")
} catch {
print("Create post or comment 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.

do {
let queryPostResult = try await Amplify.API.query(request: .get(Post.self, byIdentifier: "123"))
guard case .success(let queriedPostOptional) = queryPostResult,
let queriedPost = queriedPostOptional,
let comments = queriedPost.comments else {
print("API response: \(queryPostResult)")
return
}
try await comments.fetch()
print("Fetched \(comments.count) comments")
} catch {
print("Failed to query post or fetch comments", error)
}

Always call fetch() to load or retrieve the comments. If the comments were loaded as part of the query, it will return immediately. See Customizing Query Depth to learn how to eagerly load connected relationships.

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.

do {
let deleteCommentResult = try await Amplify.API.mutate(request: .delete(comment))
guard case .success = deleteCommentResult else {
print("API response: \(deleteCommentResult)")
return
}
// Once all comments for a post are deleted, the post can be deleted.
let deletePostResult = try await Amplify.API.mutate(request: .delete(post))
guard case .success = deletePostResult else {
print("API response: \(deletePostResult)")
return
}
print("Deleted comment and post")
} catch {
print("Failed to delete comment or 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")
}
do {
let post = Post(title: "My Post", rating: 10)
let user = User(username: "User")
let postEditor = PostEditor(post: post, user: user)
let createPostResult = try await Amplify.API.mutate(request: .create(post))
guard case .success = createPostResult else {
print("API response: \(createPostResult)")
return
}
let createUserResult = try await Amplify.API.mutate(request: .create(user))
guard case .success = createUserResult else {
print("API response: \(createUserResult)")
return
}
let createPostEditorResult = try await Amplify.API.mutate(request: .create(postEditor))
guard case .success = createPostEditorResult else {
print("API response: \(createPostEditorResult)")
return
}
} catch {
print("Failed to create post, user, or post editor", error)
}

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:

do {
let queryCommentResult = try await Amplify.API.query(request:
.get(Comment.self,
byIdentifier: "c1",
includes: { comment in
[comment.post]
}))
guard case .success(let queriedCommentOptional) = queryCommentResult,
let queriedComment = queriedCommentOptional,
let loadedPost = try await queriedComment.post else {
print("API response: \(queryCommentResult)")
return
}
print("Post: ", loadedPost)
} catch {
print("Failed to query comment with 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:

do {
let queryPostResult = try await Amplify.API.query(request:
.get(Post.self,
byIdentifier: "p1",
includes: { post in
[post.comments]
}))
guard case .success(let queriedPostOptional) = queryPostResult,
let queriedPost = queriedPostOptional,
let comments = queriedPost.comments else {
print("API response: \(queryPostResult)")
return
}
try await comments.fetch()
print("Comments: ", comments)
} catch {
print("Failed to query post with comments", 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.

let queryCommentResult = try await Amplify.API.query(request:
.get(Comment.self,
byIdentifier: "p1",
includes: { comment in
[comment.post.comments]
}))

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

let queryCommentResult = try await Amplify.API.query(request:
.get(PostEditor.self,
byIdentifier: "pe1",
includes: { postEditor in
[postEditor.post, postEditor.user]
}))

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