【问题标题】:create records with associations in sequalize在 sequelize 中创建具有关联的记录
【发布时间】:2017-02-23 00:06:42
【问题描述】:

我在sequelize中有以下模型。

var User = sequelize.define('User', {

_id: {
  type: DataTypes.INTEGER,
  allowNull: false,
  primaryKey: true,
  autoIncrement: true
},
name: DataTypes.STRING,
email: {
  type: DataTypes.STRING,
  unique: {
    msg: 'The specified email address is already in use.'
  },
  validate: {
    isEmail: true
  }
},
role: {
  type: DataTypes.STRING,
  defaultValue: 'user'
}
}

该模型具有如下一些关联/关系:

User.belongsToMany(models.Skill, {through: 'UserSkill', as: 'Skills'});

要保存新记录,我使用以下请求负载:

{
 "name": "Test User",
 "email": "d3@ddd.com",,
 "skills" : [2,3]
}

其中的技能应该代表我们在数据库中已有技能的 id 数组,我们如何保存新记录并同时验证所有技能?

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    这是一种可能对你有帮助的方法:)

    router.post('/assignSkills', function (req, res, next) {
    var record = req.body.data;
    model.users.findOne({
        where: { id: record.userId }
    }).then(function (user) {
        model.skills.findOne({  
            where: { id: record.skillId }
        }).then(function (skill) {
            user.addSkill(skill);
            res.send(user);
        });
    });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-11
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      相关资源
      最近更新 更多