Relational models
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 ACTIVE3 INACTIVE4}5
6type Post @model @auth(rules: [{allow: public}]) {7 id: ID!8 title: String!9 rating: Int!10 status: PostStatus!11 # new field with @hasMany12 comments: [Comment] @hasMany13}14
15# new model16type Comment @model {17 id: ID!18 content: String19 post: Post @belongsTo20}
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: .active5)6
7let commentWithPost = Comment(8 content: "Loving Amplify DataStore",9 post: post10)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}
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 return5 }6 // call fetch to lazy load the postResult before accessing its result7 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}
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 = comments2 .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 return5 }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}
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.
1enum PostStatus {2 ACTIVE3 INACTIVE4}5
6type Post @model {7 id: ID!8 title: String!9 rating: Int10 status: PostStatus11 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: .active4)5let user = User(6 username: "Nadia"7)8let postEditor = PostEditor(9 post: post,10 user: user11)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}