Page updated Jan 16, 2024

Relational models

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:

1enum PostStatus {
2 ACTIVE
3 INACTIVE
4}
5
6type Post @model @auth(rules: [{allow: public}]) {
7 id: ID!
8 title: String!
9 rating: Int!
10 status: PostStatus!
11 # new field with @hasMany
12 comments: [Comment] @hasMany
13}
14
15# new model
16type Comment @model {
17 id: ID!
18 content: String
19 post: Post @belongsTo
20}

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:

1let post = Post(
2 title: "My post with comments",
3 rating: 5,
4 status: .active
5)
6
7let commentWithPost = Comment(
8 content: "Loving Amplify DataStore",
9 post: post
10)
11
12do {
13 let savedPost = try await Amplify.DataStore.save(post)
14 let savedCommentWithPost = try await Amplify.DataStore.save(commentWithPost)
15} catch let error as DataStoreError {
16 print("Failed with error \(error)")
17} catch {
18 print("Unexpected error \(error)")
19}
1let post = Post(
2 title: "My post with comments",
3 rating: 5,
4 status: .active
5)
6
7let commentWithPost = Comment(
8 content: "Loving Amplify DataStore",
9 post: post)
10
11let sink = Amplify.Publisher.create { try await Amplify.DataStore.save(post) }
12 .flatMap { Amplify.Publisher.create { try await Amplify.DataStore.save(commentWithPost) } }
13 .sink {
14 if case let .failure(error) = $0 {
15 print("Error adding post and comment - \(error.localizedDescription)")
16 }
17 }
18 receiveValue: {
19 print("Post and comment saved!")
20 }

Querying relations

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

1do {
2 guard let queriedPost = try await Amplify.DataStore.query(Post.self, byId: "123"),
3 let comments = queriedPost.comments else {
4 return
5 }
6 // call fetch to lazy load the postResult before accessing its result
7 try await comments.fetch()
8 for comment in comments {
9 print("\(comment)")
10 }
11} catch let error as DataStoreError {
12 print("Failed to query \(error)")
13} catch let error as CoreError {
14 print("Failed to fetch \(error)")
15} catch {
16 print("Unexpected error \(error)")
17}
1let sink = Amplify.Publisher.create { try await Amplify.DataStore.query(Post.self, byId: "123") }.sink {
2 if case let .failure(error) = $0 {
3 print("Error retrieving post \(error.localizedDescription)")
4 }
5} receiveValue: { queriedPost in
6 guard let queriedPost = queriedPost,
7 let comments = queriedPost.comments else {
8 return
9 }
10 // call fetch to lazy load the postResult before accessing its result
11 Task {
12 do {
13 try await comments.fetch()
14 for comment in comments {
15 print("\(comment)")
16 }
17 } catch let error as CoreError {
18 print("Failed to fetch \(error)")
19 } catch {
20 print("Unexpected error \(error)")
21 }
22 }
23}

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:

1let excitedComments = comments
2 .compactMap { $0.content }
3 .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 synced to cloud. For example, the following operation would remove the Post with id 123 as well as any related comments:

1do {
2 guard let postWithComments = try await Amplify.DataStore.query(Post.self, byId: "123") else {
3 print("No post found")
4 return
5 }
6 try await Amplify.DataStore.delete(postWithComments)
7 print("Post with id 123 deleted with success")
8} catch let error as DataStoreError {
9 print("Failed with error \(error)")
10} catch {
11 print("Unexpected error \(error)")
12}
1let sink = Amplify.Publisher.create {
2 guard let postWithComments = try await Amplify.DataStore.query(Post.self, byId: "123") else {
3 return
4 }
5 try await Amplify.DataStore.delete(postWithComments)
6}.sink {
7 if case let .failure(error) = $0 {
8 print("Error deleting post and comments - \(error)")
9 }
10} receiveValue: {
11 print("Post with id 123 deleted with success")
12}

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

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.

1enum PostStatus {
2 ACTIVE
3 INACTIVE
4}
5
6type Post @model {
7 id: ID!
8 title: String!
9 rating: Int
10 status: PostStatus
11 editors: [User] @manyToMany(relationName: "PostEditor")
12}
13
14type User @model {
15 id: ID!
16 username: String!
17 posts: [Post] @manyToMany(relationName: "PostEditor")
18}
1let post = Post(
2 title: "My first post",
3 status: .active
4)
5let user = User(
6 username: "Nadia"
7)
8let postEditor = PostEditor(
9 post: post,
10 user: user
11)
12do {
13 try await Amplify.DataStore.save(post)
14 try await Amplify.DataStore.save(user)
15 try await Amplify.DataStore.save(postEditor)
16 print("Saved post, user, and postEditor!")
17} catch let error as DataStoreError {
18 print("Failed with error \(error)")
19} catch {
20 print("Unexpected error \(error)")
21}
1let post = Post(
2 title: "My first post",
3 status: .active
4)
5let user = User(
6 username: "Nadia"
7)
8let postEditor = PostEditor(
9 post: post,
10 user: user
11)
12let sink = Amplify.Publisher.create{ try await Amplify.DataStore.save(post) }
13 .flatMap { _ in
14 Amplify.Publisher.create { try await Amplify.DataStore.save(user) }
15 }
16 .flatMap { _ in
17 Amplify.Publisher.create { try await Amplify.DataStore.save(postEditor) }
18 }
19 .sink {
20 if case let .failure(error) = $0 {
21 print("Error saving post, user and postEditor: \(error.localizedDescription)")
22 }
23 }
24 receiveValue: { _ in
25 print("Saved user, post and postEditor!")
26 }

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.