节省许多许多

我徘徊,如果有任何扩展教程如何保存多对多的关系? 我发现文档比基本更多。 它缺less许多使用案例的例子。

我有两种模式:客户端和规则。 他们有n:n的关系。

客户:

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.rule, { through: 'client_rules', onDelete: 'cascade'}); } } }); 

规则:

 var Rule = sequelize.define('rule', { service_id: { type: DataTypes.INTEGER, allowNull: false }, is_allowed: { type: DataTypes.BOOLEAN, defaultValue: false }, valid_until: { type: DataTypes.DATE, allowNull: true, }, rule: { type: DataTypes.TEXT, allowNull: true }, type: { type: DataTypes.INTEGER, // 1 for company rule, 2 for individual rule allowNull: false, }, active: { type: DataTypes.BOOLEAN, defaultValue: true } },{ underscored: true, paranoid: true, classMethods: { associate:function(models){ Rule.belongsToMany(models.client, { through: 'client_rules', onDelete: 'cascade'}); Rule.belongsTo(models.service, { foreignKey: 'service_id' } ); } } }); 

现在我想为客户端创build一个新的规则。 所以我将不得不先创build规则,然后通过“client_rules”将其关联到客户端。

我如何做到这一点sequelize? 这不起作用:

 var clientID = req.user.client_id; Client.find({ id: clientID }) .then(function(client){ return client.addRule(req.body) }) .catch(function(err){ console.log(err) }) [TypeError: Cannot read property 'replace' of undefined] 

好吧,我发现如何做到这一点。 文档非常混乱。

  var clientID = req.user.client_id; return Rule.create(req.body) .then(function(newRule){ var ruleToAdd = newRule; return Client.findOne({ where: { id: clientID } }) .then(function(client){ return client.addRule(ruleToAdd) .then(function(ans){ return ruleToAdd; }) })