Page updated Nov 9, 2023

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.

Amplify Android v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Android to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

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 { id: ID! title: String! rating: Int! status: PostStatus! # New field with @hasMany comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"]) } # New model type Comment @model { id: ID! postID: ID! @index(name: "byPost") post: Post! @belongsTo(fields: ["postID"]) content: String! }
1enum PostStatus {
2 ACTIVE
3 INACTIVE
4}
5
6type Post @model {
7 id: ID!
8 title: String!
9 rating: Int!
10 status: PostStatus!
11 # New field with @hasMany
12 comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"])
13}
14
15# New model
16type Comment @model {
17 id: ID!
18 postID: ID! @index(name: "byPost")
19 post: Post! @belongsTo(fields: ["postID"])
20 content: String!
21}

Generate the models for the updated schema using the Amplify CLI.

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:

Post post = Post.builder() .title("My Post with comments") .rating(10) .status(PostStatus.ACTIVE) .build(); Comment comment = Comment.builder() .post(post) // Directly pass in the post instance .content("Loving Amplify DataStore!") .build(); Amplify.DataStore.save(post, savedPost -> { Log.i("MyAmplifyApp", "Post saved."); Amplify.DataStore.save(comment, savedComment -> Log.i("MyAmplifyApp", "Comment saved."), failure -> Log.e("MyAmplifyApp", "Comment not saved.", failure) ); }, failure -> Log.e("MyAmplifyApp", "Post not saved.", failure) );
1Post post = Post.builder()
2 .title("My Post with comments")
3 .rating(10)
4 .status(PostStatus.ACTIVE)
5 .build();
6
7Comment comment = Comment.builder()
8 .post(post) // Directly pass in the post instance
9 .content("Loving Amplify DataStore!")
10 .build();
11
12Amplify.DataStore.save(post,
13 savedPost -> {
14 Log.i("MyAmplifyApp", "Post saved.");
15 Amplify.DataStore.save(comment,
16 savedComment -> Log.i("MyAmplifyApp", "Comment saved."),
17 failure -> Log.e("MyAmplifyApp", "Comment not saved.", failure)
18 );
19 },
20 failure -> Log.e("MyAmplifyApp", "Post not saved.", failure)
21);

Querying relations

Amplify.DataStore.query(Comment.class, Post.STATUS.eq(PostStatus.ACTIVE), matches -> { while (matches.hasNext()) { Comment comment = matches.next(); Log.i("MyAmplifyApp", "Content: " + comment.getContent()); } }, failure -> Log.e("MyAmplifyApp", "Query failed.", failure) );
1Amplify.DataStore.query(Comment.class, Post.STATUS.eq(PostStatus.ACTIVE),
2 matches -> {
3 while (matches.hasNext()) {
4 Comment comment = matches.next();
5 Log.i("MyAmplifyApp", "Content: " + comment.getContent());
6 }
7 },
8 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
9);

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:

QueryOptions queryOptions = null; try { queryOptions = Where.identifier(Post.class, "123"); } catch (AmplifyException e) { Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e); } if (queryOptions != null) { Amplify.DataStore.query(Post.class, queryOptions, match -> { if (match.hasNext()) { Post post = match.next(); Amplify.DataStore.delete(post, deleted -> Log.i("MyAmplifyApp", "Post deleted."), failure -> Log.e("MyAmplifyApp", "Delete failed.", failure) ); } }, failure -> Log.e("MyAmplifyApp", "Query failed.", failure) ); }
1QueryOptions queryOptions = null;
2try {
3 queryOptions = Where.identifier(Post.class, "123");
4} catch (AmplifyException e) {
5 Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e);
6}
7
8if (queryOptions != null) {
9 Amplify.DataStore.query(Post.class, queryOptions,
10 match -> {
11 if (match.hasNext()) {
12 Post post = match.next();
13 Amplify.DataStore.delete(post,
14 deleted -> Log.i("MyAmplifyApp", "Post deleted."),
15 failure -> Log.e("MyAmplifyApp", "Delete failed.", failure)
16 );
17 }
18 },
19 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
20 );
21}

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") }
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}
Post post = Post.builder() .title("My First Post") .build(); User editor = User.builder() .username("Nadia") .build(); PostEditor postEditor = PostEditor.builder() .post(post) .user(editor) .build(); Amplify.DataStore.save(post, savedPost -> { Log.i("MyAmplifyApp", "Post saved."); Amplify.DataStore.save(editor, savedEditor -> { Log.i("MyAmplifyApp", "Editor saved."); Amplify.DataStore.save(postEditor, saved -> Log.i("MyAmplifyApp", "PostEditor saved."), failure -> Log.e("MyAmplifyApp", "PostEditor not saved.", failure) ); }, failure -> Log.e("MyAmplifyApp", "Editor not saved.", failure) ); }, failure -> Log.e("MyAmplifyApp", "Post not saved.", failure) );
1Post post = Post.builder()
2 .title("My First Post")
3 .build();
4
5User editor = User.builder()
6 .username("Nadia")
7 .build();
8
9PostEditor postEditor = PostEditor.builder()
10 .post(post)
11 .user(editor)
12 .build();
13
14Amplify.DataStore.save(post,
15 savedPost -> {
16 Log.i("MyAmplifyApp", "Post saved.");
17 Amplify.DataStore.save(editor,
18 savedEditor -> {
19 Log.i("MyAmplifyApp", "Editor saved.");
20 Amplify.DataStore.save(postEditor,
21 saved -> Log.i("MyAmplifyApp", "PostEditor saved."),
22 failure -> Log.e("MyAmplifyApp", "PostEditor not saved.", failure)
23 );
24 },
25 failure -> Log.e("MyAmplifyApp", "Editor not saved.", failure)
26 );
27 },
28 failure -> Log.e("MyAmplifyApp", "Post not saved.", failure)
29);

This example illustrates the complexity of working with multiple sequential save operations. To remove the nested callbacks, consider using Amplify's support for RxJava or Coroutines.