belongs to associations
Overview
Belongs to associations are to be used when the model in question is related to another model, and contains a foreign key to that model within its table. An example of a belongs to would be in the case of a User and Post model, where a User can write many Posts, and each Post would contain a field (called a foreign key) which points back to the id field of a User who owns it. In this context, we would say that the Post belongs to the User:
export default class Post extends ApplicationModel {
...
@deco.BelongsTo('User')
public user: User
public userId: DreamColumn<Post, 'userId'>
}
Options
optional
BelongsTo associations are required by default (and should have a corresponding not-null declaration on the foreign key column). To make an association optional, pass the optional: true option (and ensure that the column allows null values):
export default class Post extends ApplicationModel {
...
@deco.BelongsTo('User', { optional: true })
public user: User | null
public userId: DreamColumn<Post, 'userId'>
}
Required BelongsTo associations are a two-way non-nullable contract: the foreign key should be not-null in the database, the model property is not nullable, and serializers/request shapes infer that requiredness. If a required belongs-to is missing because an internal mechanism bypassed the contract, Dream raises MissingRequiredBelongsToAssociation; fix the model relationship (dependent: 'destroy' on the inverse or optional: true), not the serializer.
Foreign key (on option)
By default, the foreign key is derived from the association name. E.g., in the example below, the default foreign key would be userId. This can be overridden by including an explicit on: '<camelized-column-name-on-this-table>' option:
export default class Post extends ApplicationModel {
...
@deco.BelongsTo('User', { on: 'myUserId' })
public user: User
public myUserId: number
}
Primary key override
By default, the column that the foreign key points to is returned by the primaryKey getter
(and defaults to id). For associations that point to something other than the primary key,
this can be overridden by passing the primaryKeyOverride: '<column-name-on-target-table>' option.
export default class Post extends ApplicationModel {
...
@deco.BelongsTo('User', { primaryKeyOverride: 'uuid' })
public user: User
public userId: number
}