node.js - Sequelize 保存多对多

标签 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]

最佳答案

好的,我知道怎么做了。这些文档非常困惑。

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

关于node.js - Sequelize 保存多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29051082/

相关文章:

node.js - API Gateway 二进制支持 .wav 文件

node.js - 如何在docker compose secret中使用主目录中的文件?

sql - 聚合排名或索引 >= N 的行

node.js - 强制 Sequelize 在 Express 路由中更新 req.user

node.js - Sequelize where-clause 运算符不产生预期的输出

mysql - SET FOREIGN_KEY_CHECKS = 0 在 Sequelize 迁移中不起作用

node.js - 在 Node js 中使用 log4js 将日志写入文件

node.js - npm 错误!解析 '..."jscs 附近时 JSON 输入意外结束“:"~3.0.7","moch'

python - sqlalchemy 回滚的原因

regex - POSTGRESQL 名称中至少有 8 个字符,带有 LIKE 或 REGEX