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:
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 modeltype 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!") }