Skip to content

Commit 1b6b71b

Browse files
committed
chore: added cascade delete sections in Has One and Has Many data model relationships
1 parent b4cbc15 commit 1b6b71b

File tree

1 file changed

+43
-0
lines changed
  • src/pages/[platform]/build-a-backend/data/data-modeling/relationships

1 file changed

+43
-0
lines changed

Diff for: src/pages/[platform]/build-a-backend/data/data-modeling/relationships/index.mdx

+43
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,29 @@ do {
439439

440440
</InlineFilter>
441441

442+
### Handling orphaned foreign keys on parent record deletion in "Has Many" relationship
443+
444+
<InlineFilter filters={["javascript", "angular", "react-native", "react", "nextjs", "vue"]}>
445+
446+
```ts
447+
// Get the IDs of the related members.
448+
const { data: teamWithMembers } = await client.models.Team.get(
449+
{ id: teamId},
450+
{ selectionSet: ["id", "members.*"] },
451+
);
452+
453+
// Delete Team
454+
await client.models.Team.delete({ id: teamWithMembers.id });
455+
456+
// Delete all members in parallel
457+
await Promise.all(
458+
teamWithMembers.members.map(member =>
459+
client.models.Member.delete({ id: member.id })
460+
));
461+
```
462+
463+
</InlineFilter>
464+
442465
## Model a "one-to-one" relationship
443466

444467
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**.
@@ -794,6 +817,26 @@ val cart = Amplify.API.query(
794817

795818
</InlineFilter>
796819

820+
### Handling orphaned foreign keys on parent record deletion in "Has One" relationship
821+
822+
<InlineFilter filters={["javascript", "angular", "react-native", "react", "nextjs", "vue"]}>
823+
824+
```ts
825+
// Get the customer with their associated cart
826+
const { data: customerWithCart } = await client.models.Customer.get(
827+
{ id: customerId },
828+
{ selectionSet: ["id", "activeCart.*"] },
829+
);
830+
831+
// Delete Cart if exists
832+
await client.models.Cart.delete({ id: customerWithCart.activeCart.id });
833+
834+
// Delete the customer
835+
await client.models.Customer.delete({ id: customerWithCart.id });
836+
```
837+
838+
</InlineFilter>
839+
797840

798841
## Model a "many-to-many" relationship
799842
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.

0 commit comments

Comments
 (0)