sequelize include association code example
Example 1: sequelize include only
Payment.findAll({
where: {
DairyId: req.query.dairyid
},
attributes: {
exclude: ['createdAt', 'updatedAt']
},
include: {
model: Customer,
attributes:['customerName', 'phoneNumber']
}
})
Example 2: 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
}
}]