In Amplify DataStore (formerly Amplify API, Amplify Model), when you define a one-to-one relationship using @belongsTo, the related field (foreign key) is not automatically included in the generated TypeScript model by default. However, you can manually add the field to the model definition to establish the one-to-one relationship and use it for querying.

Let's say you have two models, User and Profile, where a User has one Profile and a Profile belongs to one User. Here's how you can define the one-to-one relationship and include the userId field (foreign key) in the generated TypeScript model:

  1. Define the Models:
typescript
// src/models/User.ts import { model, property, hasOne } from '@aws-amplify/datastore'; @model export class User { @property({ id: true }) // Assuming this is the primary key of User id: string; @property() name: string; @hasOne(() => Profile) profile: Profile; // One-to-one relationship with Profile model } // src/models/Profile.ts import { model, property, belongsTo } from '@aws-amplify/datastore'; @model export class Profile { @property({ id: true }) // Assuming this is the primary key of Profile id: string; @property() bio: string; @belongsTo(() => User) // Belongs to User model (one-to-one) userId: string; // Foreign key for the one-to-one relationship }
  1. Manually Add Foreign Key to User Model: Since the userId field is not automatically generated in the User model due to the one-to-one relationship being defined on the Profile model, you need to manually add the userId field to the User model to establish the relationship.
typescript
// src/models/User.ts import { model, property, hasOne } from '@aws-amplify/datastore'; import { Profile } from './Profile'; @model export class User { @property({ id: true }) // Assuming this is the primary key of User id: string; @property() name: string; @hasOne(() => Profile) profile: Profile; // One-to-one relationship with Profile model // Manually add userId field (foreign key) @property() userId: string; }

By adding the userId field to the User model, you can now establish the one-to-one relationship and use it for querying or accessing related data. Note that you need to set the correct value for userId to create a one-to-one relationship between a User and a Profile.

Keep in mind that this manual modification may need to be repeated whenever you regenerate the TypeScript models using Amplify CLI, as the changes will be overwritten during the regeneration process.

Have questions or queries?
Get in Touch