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.
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 totrue
.
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.
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