Sequelize associations tutorial code example
Example 1: sequelize associations
const User = sequelize.define('user', { name: DataTypes.STRING }, { timestamps: false });
const Task = sequelize.define('task', { name: DataTypes.STRING }, { timestamps: false });
const Tool = sequelize.define('tool', {
name: DataTypes.STRING,
size: DataTypes.STRING
}, { timestamps: false });
User.hasMany(Task);
Task.belongsTo(User);
User.hasMany(Tool, { as: 'Instruments' });
const tasks = await Task.findAll({ include: User });
[{
"name": "A Task",
"id": 1,
"userId": 1,
"user": {
"name": "John Doe",
"id": 1
}
}]
Example 2: belongsToMany sequelize best pratice
module.exports = function(sequelize, DataTypes) {
const TagPostGenre = sequelize.define('tag_post_genre', {
tag_post_genre_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.INTEGER(11),
primaryKey: true
},
post_id: {
type: DataTypes.INTEGER(11),
primaryKey: false,
references: {
model: 'post',
key: 'post_id'
},
onDelete: 'cascade',
onUpdate: 'cascade',
unique: 'unique-genre-per-post'
},
genre_id: {
type: DataTypes.INTEGER(11),
primaryKey: false,
references: {
model: 'genre',
key: 'genre_id'
},
onDelete: 'cascade',
onUpdate: 'cascade',
unique: 'unique-genre-per-post'
},
}, {
timestamps: true,
underscored: true,
tableName: 'tag_post_genre'
});
return TagPostGenre;
};