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

Page updated Apr 29, 2024

Relational models

Amplify iOS v1 is deprecated as of June 1st, 2024. No new features or bug fixes will be added. Dependencies may become outdated and potentially introduce compatibility issues.

Please use the latest version (v2) of Amplify Library for Swift to get started. Refer to the upgrade guide for instructions on upgrading your application to the latest version.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

The @hasOne and @hasMany directives do not support referencing a model which then references the initial model via @hasOne or @hasMany if DataStore is enabled.

DataStore has the capability to handle relationships between Models, such as has one, has many, belongs to. In GraphQL this is done with the @hasOne, @hasMany and @index directives as defined in the GraphQL Transformer documentation.

Updated schema

For the examples below with DataStore let's add a new model to the sample schema:

enum PostStatus {
ACTIVE
INACTIVE
}
type Post @model @auth(rules: [{allow: public}]) {
id: ID!
title: String!
rating: Int!
status: PostStatus!
# new field with @hasMany
comments: [Comment] @hasMany
}
# new model
type Comment @model {
id: ID!
content: String
post: Post @belongsTo
}

Saving relations

In order to save connected models, you will create an instance of the model you wish to connect and pass its ID to DataStore.save:

let postWithComments = Post(title: "My post with comments",
rating: 5,
status: .active)
let comment = Comment(content: "Loving Amplify DataStore", post: postWithComments)
Amplify.DataStore.save(postWithComments) { postResult in
switch postResult {
case .failure(let error):
print("Error adding post - \(error.localizedDescription)")
case .success:
Amplify.DataStore.save(comment) { commentResult in
switch commentResult {
case .success:
print("Comment saved!")
case .failure(let error):
print("Error adding comment - \(error.localizedDescription)")
}
}
}
}
let postWithComments = Post(title: "My post with comments",
rating: 5,
status: .active)
let comment = Comment(content: "Loving Amplify DataStore", post: postWithComments)
let sink = Amplify.DataStore.save(postWithComments)
.flatMap { Amplify.DataStore.save(comment) }
.sink {
if case let .failure(error) = $0 {
print("Error adding post and comment - \(error.localizedDescription)")
}
}
receiveValue: {
print("Post and comment saved!")
}

Querying relations

Models with one-to-many connections are lazy-loaded when accessing the connected property, so accessing a relation is as simple as:

Amplify.DataStore.query(Post.self, byId: "123") {
switch $0 {
case .success(let post):
if let postWithComments = post {
if let comments = postWithComments.comments {
for comment in comments {
print(comment.content)
}
}
} else {
print("Post not found")
}
case .failure(let error):
print("Post not found - \(error.localizedDescription)")
}
}
let sink = Amplify.DataStore.query(Post.self, byId: "123")
.compactMap { $0?.comments }
.flatMap { $0.loadAsPublisher() }
.sink {
if case let .failure(error) = $0 {
print("Error retrieving post \(error.localizedDescription)")
}
}
receiveValue: {
for comment in $0 {
print(comment.content)
}
}

The connected properties are of type List<M>, where M is the model type, and that type is a custom Swift Collection, which means that you can filter, map, etc:

let excitedComments = postWithComments
.comments?
.compactMap { $0.content }
.filter { $0.contains("Wow!") }

Deleting relations

When you delete a parent object in a one-to-many relationship, the children will also be removed from the DataStore and mutations for this deletion will be sent over the network. For example, the following operation would remove the Post with id 123 as well as any related comments:

Amplify.DataStore.query(Post.self, byId: "123") {
switch $0 {
case .success(let postWithComments):
// postWithComments might be nil, unwrap the optional appropriately
Amplify.DataStore.delete(postWithComments!) { deleteResult in
switch deleteResult {
case .success:
print("Post with id 123 deleted with success")
case .failure(let error):
print("Error deleting post and comments - \(error.localizedDescription)")
}
}
case .failure(let error):
print("Error fetching post with id 123 - \(error.localizedDescription)")
}
}
let sink = Amplify.DataStore.query(Post.self, byId: "123")
// postWithComments might be nil, unwrap the optional appropriately
.compactMap { $0 }
.flatMap { postWithComments in
Amplify.DataStore.delete(postWithComments)
}
.sink {
if case let .failure(error) = $0 {
print("Error deleting post and comments - \(error.localizedDescription)")
}
}
receiveValue: {
print("Post with id 123 deleted with success")
}

However, in a many-to-many relationship the children are not removed and you must explicitly delete them.

Many-to-many

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.

enum PostStatus {
ACTIVE
INACTIVE
}
type Post @model {
id: ID!
title: String!
rating: Int
status: PostStatus
editors: [User] @manyToMany(relationName: "PostEditor")
}
type User @model {
id: ID!
username: String!
posts: [Post] @manyToMany(relationName: "PostEditor")
}
let post = Post(title: "My post with comments",
rating: 5,
status: .active)
let editor = User(username: "Nadia")
Amplify.DataStore.save(post) { postResult in
switch postResult {
case .failure(let error):
print("Error adding post - \(error.localizedDescription)")
case .success:
Amplify.DataStore.save(editor) { editorResult in
switch editorResult {
case .failure(let error):
print("Error adding user - \(error.localizedDescription)")
case .success:
let postEditor = PostEditor(post: post, editor: editor)
Amplify.DataStore.save(postEditor) { postEditorResult in
switch postEditorResult {
case .failure(let error):
print("Error saving postEditor - \(error.localizedDescription)")
case .success:
print("Saved user, post and postEditor!")
}
}
}
}
}
}
let post = Post(title: "My post with comments",
rating: 5,
status: .active)
let editor = User(username: "Nadia")
let sink = Amplify.DataStore.save(post)
.flatMap { _ in Amplify.DataStore.save(editor) }
.flatMap { _ in Amplify.DataStore.save(PostEditor(post: post, editor: editor)) }
.sink {
if case let .failure(error) = $0 {
print("Error saving post, user and postEditor: \(error.localizedDescription)")
}
}
receiveValue: { _ in
print("Saved user, post and postEditor!")
}

This example illustrates the complexity of working with multiple dependent persistence operations. The callback model is flexible but imposes some challenges when dealing with such scenarios. Prefer to use the Combine model if your app supports iOS 13 or higher. If not, the recommendation is that you use multiple functions to simplify the code.