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

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 schema.graphql file located by default at amplify/backend/{api_name}/:

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!
}

After that, regenerate the models with the following console command:

amplify codegen models

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:

import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> savePostAndComment() async {
final post = Post(
title: 'My Post with comments',
rating: 10,
status: PostStatus.ACTIVE,
);
final comment = Comment(
post: post, // associate the comment to the post
content: 'Loving Amplify DataStore!',
);
try {
// Make sure to safe the parent Post first
await Amplify.DataStore.save(post);
await Amplify.DataStore.save(comment);
} on DataStoreException catch (e) {
safePrint('Something went wrong querying posts: ${e.message}');
}
}

Querying relations

In order to retrieve all models that are related to a parent model, you can use query predicates with the query API:

import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> fetchAllCommentsForPostId(String postId) async {
try {
final comments = await Amplify.DataStore.query(
Comment.classType,
where: Comment.POST.eq(postId),
);
safePrint('Comments: $comments');
} on DataStoreException catch (e) {
safePrint('Something went wrong querying posts: ${e.message}');
}
}

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:

import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> deletePostWithID123AndItsComments(String id) async {
try {
final post = (await Amplify.DataStore.query(
Post.classType,
where: Post.ID.eq(id),
))
.first;
// DataStore also deletes all associated comments with this operation
await Amplify.DataStore.delete(post);
} on DataStoreException catch (e) {
safePrint('Something went wrong deleting models: ${e.message}');
}
}

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.

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")
}

Add the model above to the schema.graphql file located by default at amplify/backend/{api_name}/ and regenerate the models again with the following command:

amplify codegen models

Once it is regenerated, save your posts with many-to-many mode like the following:

import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> savePostAndEditor() async {
final post = Post(
title: 'My First Post',
rating: 10,
status: PostStatus.INACTIVE,
);
final editor = User(username: 'Nadia');
final postEditor = PostEditor(post: post, user: editor);
try {
// first you save the post
await Amplify.DataStore.save(post);
// secondly, you save the editor/user
await Amplify.DataStore.save(editor);
// then you save the model that links a post with an editor
await Amplify.DataStore.save(postEditor);
} on DataStoreException catch (e) {
safePrint('Something went wrong saving model: ${e.message}');
}
}