Skip to content

Class: BelongsTo<OM, TM, PKT, FM, PKF>

Represents a relationship between two models where the ID of the foreign model is stored as a property of the originating model.

Description

For example, a user has a single profile:

In your configuration you would have:

typescript
{
  ...
  models: {
      users: {
        schema: '++id, email, createdAt, updatedAt',
        properties: ['id', 'email', 'password', 'createdAt', 'updatedAt'],
        primaryKey: 'id',
      },
      profiles: {
        schema: '++id, user_id, full_name, avatar_url',
        properties: ['id', 'user_id', 'full_name', 'avatar_url'],
        relationships: {
          user: [BelongsTo, 'users', 'user_id'], 
        }
      }
  },
  ...
}

Which will then allow you to access the user of a profile from the user accessor on the profile model: profile.user.

Remarks

The inverse of this relationship can be either HasOne or HasMany relationship. Configured using the BelongsToConfiguration tuple.

Extends

Type Parameters

Type ParameterDescription
OM extends Record<string, PlainObject>the map of all models in the database
TM extends StringKeyOf<OM>the table of the originating model
PKT extends StringKeyOf<OM[TM]>the property used as the primary key in the originating model
FM extends StringKeyOf<OM>the table of the foreign model
PKF extends StringKeyOf<OM[FM]>the property used as the primary key in the foreign model