Sequelize拯救了许多人

时间:2015-03-14 16:10:09

标签: node.js postgresql sequelize.js

如果有任何关于如何保存多对多关系的扩展教程,我就会徘徊?我发现文档不仅仅是基本的。它缺少许多用例示例。

我有两个模型:客户端和规则。他们有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' } );

      }
    }
  });

现在我想为客户创建一个新规则。因此,我必须首先创建规则,然后通过'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]

1 个答案:

答案 0 :(得分:1)

好的,我发现了怎么做。文档非常令人困惑。

    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;
            })
    })