简体   繁体   English

在sequalize中创建具有关联的记录

[英]create records with associations in sequalize

i have the following model in sequelize. 我在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'
}
}

the model has some asssoications/relations as follows: 该模型有一些协助/关系如下:

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

to save a new record i use the following request payload: 要保存新记录,我使用以下请求有效负载:

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

where skills should represent an array of ids for skills we already have in DB, how can we save the new record and validate all skills at the same time? 技能应该代表我们在数据库中已经拥有的技能的一系列ID,我们如何保存新记录并同时验证所有技能?

This is the one way may be it helps you :) 这是一种方式可能会帮助你:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM