BelongsTo Relationship
The BelongsTo relationship represents an inverse one-to-one or many-to-one relationship where the current model holds a reference to another model.
Explanation
For example, a Profile belongs to a User:
Defining the Relationship
The relationship is defined in your model configuration under the relationships
property as a tuple:
typescript
[BelongsTo, foreignModelTable: string, foreignKey: string, originatingPrimaryKey?: string, foreignPrimaryKey?: string]
Required Parameters
BelongsTo
: The relationship typeforeignModelTable
: The table name of the related modelforeignKey
: The foreign key in the current model that references the related model
Optional Parameters
originatingPrimaryKey
: The primary key in the current model (defaults to 'id')foreignPrimaryKey
: The primary key in the foreign model (defaults to 'id')
Example
typescript
{
models: {
users: {
schema: '++id, email, createdAt, updatedAt',
properties: ['id', 'email', 'password'],
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'],
}
}
}
}
In this example:
- The Profile model has a
user_id
foreign key that references the User model'sid
- The relationship is defined as
[BelongsTo, 'users', 'user_id']
where:'users'
is theforeignModelTable
'user_id'
is theforeignKey
- The primary keys default to 'id' since they're not specified
Accessing the Relationship
typescript
// Get the profile's user
const profile = await Profile.find(1)
const user = await profile.user
// The relationship is reactive
profile.user.onChange((newUser) => {
console.log('User updated:', newUser)
})
// You can also eager load the relationship
const profiles = await Profile.query()
.with('user')
.fetch()