Phone.belongsTo(Person)
Source
Target
Alternatively, we can think of the two models as owner and possession
Possession
(in this case)
Owner
(in this case)
Phone.belongsTo(Person) | Person.hasOne(Phone) |
Foreign Key appears on the source model | Foreign Key appears on the target model |
There are two methods to create 1:1 associations:
In both methods, the possession model (Phone) holds the foreign key
These methods always assign association methods (i.e. get, set, create) to the source
.hasMany creates a 1:m relationship where:
.belongsToMany creates a m:m relationship where:
Aliasing provides context behind associations, for example:
At times, foreign keys may be necessary to preserve context and prevent repetition
Person.findById(123, {
include: [{model: Pet}]
})
.then(function(response) {
return response.data
});
.catch(console.error);
Person.addScope('defaultScope', {
include: [{model: Pet}]
}, {
override: true
});
In Finder | In Model |
Both methods will add a Pet object as a property on relevant instances of Person