The Sequelize belongsTo() method allows you to create a One-To-One (1:1) relationship between two Sequelize models.
The method is called from a source model and pointed towards the model passed as its argument.
For example, suppose we have a customer and address models defined like this:
const customer = sequelize.define(
“customer”,
{ firstName: Sequelize.STRING },
record_row_id:
{
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
unique: true
},
{ timestamps: false }
);
const address = sequelize.define(
“Address”,
record_row_id:
{
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
customer_row_id:
{
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: customer,
key: ‘record_row_id’
}
},
{ timestamps: false }
);
The defined models above will represent the Customer and Address tables respectively. This is because Sequelize uses the plural forms of the model names when looking for the tables by default.
You can make the address model belongs to the customer model by calling the belongsTo() method from the address model like this:
db.address.belongsTo(db.customer, {
foreignKey: “customer_row_id”,
AS: “customer”,
targetKey: “record_row_id”
});
The belongsTo() method above will associate the Address model with the customer model, adding the record_row_id attribute to the address model as the foreign key constraint.
The belongsTo() method also provide several options to let you modify the relationship