Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated May 1, 2024

Modeling relationships

When modeling application data, you often need to establish relationships between different data models. In Amplify Data, you can create one-to-many, one-to-one, and many-to-many relationships in your Data schema. On the client-side, Amplify Data allows you to lazy or eager load of related data.

Types of relationships

RelationshipCodeDescriptionExample
one to manya.hasMany(...) & a.belongsTo(...)Creates a one-to-many relationship between two models.A Team has many Members. A Member belongs to a Team.
one to onea.hasOne(...) & a.belongsTo(...)Creates a one-to-one relationship between two models.A Customer has one Cart. A Cart belongs to one Customer.
many to manyTwo a.hasMany(...) & a.belongsTo(...) on join tablesCreate two one-to-many relationships between the related models in a join table.A Post has many Tags. A Tag has many Posts.

Model one-to-many relationships

Create a one-to-many relationship between two models using the hasMany() and belongsTo() method. In the example below, a Team has many Members and a Member belongs to exactly one Team.

  1. Create a reference field called teamId on the Member model. This reference field's type MUST match the type of Team's identifier. In this case, it's an auto-generated id: a.id().required() field.
  2. Add a relationship field called team that references the teamId field. This allows you to query for the team information from the Member model.
  3. Add a relationship field called members that references the teamId field on the Member model.
1const schema = a.schema({
2 Member: a.model({
3 name: a.string().required(),
4 // 1. Create a reference field
5 teamId: a.id(),
6 // 2. Create a belongsTo relationship with the reference field
7 team: a.belongsTo('Team', 'teamId'),
8 })
9 .authorization(allow => [allow.publicApiKey()]),
10
11 Team: a.model({
12 mantra: a.string().required(),
13 // 3. Create a hasMany relationship with the reference field
14 // from the `Member`s model.
15 members: a.hasMany('Member', 'teamId'),
16 })
17 .authorization(allow => [allow.publicApiKey()]),
18});

Create a "Has Many" relationship between records

1const { data: team } = await client.models.Team.create({
2 mantra: 'Go Frontend!',
3});
4
5const { data: member } = await client.models.Member.create({
6 name: "Tim",
7 teamId: team.id,
8});

Update a "Has Many" relationship between records

1const { data: newTeam } = await client.models.Team.create({
2 mantra: 'Go Fullstack',
3});
4
5await client.models.Member.update({
6 id: "MY_MEMBER_ID",
7 teamId: newTeam.id,
8});

Delete a "Has Many" relationship between records

If your reference field is not required, then you can "delete" a one-to-many relationship by setting the relationship value to null.

1await client.models.Member.update({
2 id: "MY_MEMBER_ID",
3 teamId: null,
4});

Lazy load a "Has Many" relationship

1const { data: team } = await client.models.Team.get({ id: "MY_TEAM_ID"});
2
3const { data: members } = await team.members();
4
5members.forEach(member => console.log(member.id));

Eagerly load a "Has Many" relationship

1const { data: teamWithMembers } = await client.models.Team.get(
2 { id: "MY_TEAM_ID" },
3 { selectionSet: ["id", "members.*"] },
4);
5
6teamWithMembers.members.forEach(member => console.log(member.id));

Model a "one-to-one" relationship

Create a one-to-one relationship between two models using the hasOne() and belongsTo() methods. In the example below, a Customer has a Cart and a Cart belongs to a Customer.

  1. Create a reference field called customerId on the Cart model. This reference field's type MUST match the type of Customer's identifier. In this case, it's an auto-generated id: a.id().required() field.
  2. Add a relationship field called customer that references the customerId field. This allows you to query for the customer information from the Cart model.
  3. Add a relationship field called activeCart that references the customerId field on the Cart model.
1const schema = a.schema({
2 Cart: a.model({
3 items: a.string().required().array(),
4 // 1. Create reference field
5 customerId: a.id(),
6 // 2. Create relationship field with the reference field
7 customer: a.belongsTo('Customer', 'customerId'),
8 }),
9 Customer: a.model({
10 name: a.string(),
11 // 3. Create relationship field with the reference field
12 // from the Cart model
13 activeCart: a.hasOne('Cart', 'customerId')
14 }),
15});

Create a "Has One" relationship between records

To create a "has one" relationship between records, first create the parent item and then create the child item and assign the parent.

1const { data: customer, errors } = await client.models.Customer.create({
2 name: "Rene",
3});
4
5
6const { data: cart } = await client.models.Cart.create({
7 items: ["Tomato", "Ice", "Mint"],
8 customerId: customer?.id,
9});

Update a "Has One" relationship between records

To update a "Has One" relationship between records, you first retrieve the child item and then update the reference to the parent to another parent. For example, to reassign a Cart to another Customer:

1const { data: newCustomer } = await client.models.Customer.create({
2 name: 'Ian',
3});
4
5await client.models.Cart.update({
6 id: cart.id,
7 customerId: newCustomer?.id,
8});

Delete a "Has One" relationship between records

You can set the relationship field to null to delete a "Has One" relationship between records.

1await client.models.Cart.update({
2 id: project.id,
3 customerId: null,
4});

Lazy load a "Has One" relationship

1const { data: cart } = await client.models.Cart.get({ id: "MY_CART_ID"});
2const { data: customer } = await cart.customer();

Eagerly load a "Has One" relationship

1const { data: cart } = await client.models.Cart.get(
2 { id: "MY_CART_ID" },
3 { selectionSet: ['id', 'customer.*'] },
4);
5
6console.log(cart.customer.id)

Model a "many-to-many" relationship

In order to create a many-to-many relationship between two models, you have to create a model that serves as a "join table". This "join table" should contain two one-to-many relationships between the two related entities. For example, to model a Post that has many Tags and a Tag has many Posts, you'll need to create a new PostTag model that represents the relationship between these two entities.

1const schema = a.schema({
2 PostTag: a.model({
3 // 1. Create reference fields to both ends of
4 // the many-to-many relationship
7 // 2. Create relationship fields to both ends of
8 // the many-to-many relationship using their
9 // respective reference fields
12 }),
13 Post: a.model({
14 title: a.string(),
15 content: a.string(),
16 // 3. Add relationship field to the join model
17 // with the reference of `postId`
19 }),
20 Tag: a.model({
21 name: a.string(),
22 // 4. Add relationship field to the join model
23 // with the reference of `tagId`
25 }),
26}).authorization(allow => [allow.publicApiKey()]);

Model multiple relationships between two models

Relationships are defined uniquely by their reference fields. For example, a Post can have separate relationships with a Person model for author and editor.

1const schema = a.schema({
2 Post: a.model({
3 title: a.string().required(),
4 content: a.string().required(),
9 }),
10 Person: a.model({
11 name: a.string(),
14 }),
15}).authorization(allow => [allow.publicApiKey()]);

On the client-side, you can fetch the related data with the following code:

1const client = generateClient<Schema>();
2
3const { data: post } = await client.models.Post.get({ id: "SOME_POST_ID" });
4
5const { data: author } = await post?.author();
6const { data: editor } = await post?.editor();

Model relationships for models with sort keys in their identifier

In cases where your data model uses sort keys in the identifier, you need to also add reference fields and store the sort key fields in the related data model:

1const schema = a.schema({
2 Post: a.model({
3 title: a.string().required(),
4 content: a.string().required(),
5 // Reference fields must correspond to identifier fields.
10 }),
11 Person: a.model({
12 name: a.string().required(),
13 dateOfBirth: a.date().required(),
14 // Must reference all reference fields corresponding to the
15 // identifier of this model.
16 authoredPosts: a.hasMany('Post', ['authorName', 'authorDoB']),
18}).authorization(allow => [allow.publicApiKey()]);

Make relationships required or optional

Amplify Data's relationships use reference fields to determine if a relationship is required or not. If you mark a reference field as required, then you can't "delete" a relationship between two models. You'd have to delete the related record as a whole.

1const schema = a.schema({
2 Post: a.model({
3 title: a.string().required(),
4 content: a.string().required(),
5 // You must supply an author when creating the post
6 // Author can't be set to `null`.
8 author: a.belongsTo('Person', 'authorId'),
9 // You can optionally supply an editor when creating the post.
10 // Editor can also be set to `null`.
12 editor: a.belongsTo('Person', 'editorId'),
13 }),
14 Person: a.model({
15 name: a.string(),
18 }),
19})