Reputation: 6941
This is my model definition of Room table
sequelize.define("room", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: DataTypes.STRING,
business_id: {
type: DataTypes.INTEGER,
references: {
model:"business,
key: "id"
}
}
});
And this is of business
sequelize.define("business", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: DataTypes.STRING,
});
Now consider I have id
of the room with me and I want to get business related to that using the foreign key. In normal SQL
I would easily do this using inner join
I know that there is something like Association used in Sequelize but then what is the use of defining a reference in the model definition?
Upvotes: 0
Views: 59
Reputation: 58523
As per the DOC :
Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.
Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).
- hasOne - adds a foreign key to the target and singular association mixins to the source.
- belongsTo - add a foreign key and singular association mixins to the source.
- hasMany - adds a foreign key to target and plural association mixins to the source.
- belongsToMany - creates an N:M association with a join table and adds plural association mixins to the source. The junction table is created with sourceId and targetId.
Creating an association will add a foreign key constraint to the attributes. All associations use CASCADE on update and SET NULL on delete, except for n:m, which also uses CASCADE on delete.
I think this will clear your doubts.
Upvotes: 1