I need some help to get my head around the sequelize many to many relationship.
I have to models, clients and services (many to many). Now I would like to load all services offered by one client (via client id). How does the condition with include have to look like to achieve this?
Service:
var Service = sequelize.define('service', {
title: {
type: DataTypes.STRING(200),
allowNull: false
}
},{
paranoid: true,
underscored: true,
classMethods: {
associate:function(models){
Service.belongsToMany(models.client, { through: 'client_services' });
Service.hasMany(models.rule, { foreignKey: 'service_id' })
}
}
});
Client:
var Client = sequelize.define('client', {
title: {
type: DataTypes.STRING(200),
allowNull: false
},
company: {
type: DataTypes.STRING(200),
allowNull: false
},
vendor: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
consumer: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},
address_id: {
type: DataTypes.INTEGER,
allowNull: true
}
},{
paranoid: true,
underscored: true,
classMethods: {
associate:function(models){
Client.hasMany(models.service, { through: 'client_services'});
}
}
});
In my Controller (doesn't work err: [Error: client (client) is not associated to service!]):
var condition = {
where: { 'client.id': req.user.client_id },
include: [{ model: Client, as: 'client' }]
}
Service.findAll(condition)
.then(responseWithResult(res))
Ok the where clause needs to be in the include with the model:
var condition = {
include: [{ model: Client, where: { 'id': req.user.client_id } }]
}
Service.findAll(condition)
.then(responseWithResult(res))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.