create records with associations

11 views
Skip to first unread message

Wajid Afaneh

unread,
Dec 26, 2015, 3:13:49 PM12/26/15
to Sequelize
Hello,

i have the following model:

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 associations 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": "example@example.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?

Thanks,

Mick Hansen

unread,
Dec 29, 2015, 7:14:29 AM12/29/15
to Wajid Afaneh, Sequelize
You could add an afterCreate hooks to the model that looks for those values and does the necessary calls.
--
Mick Hansen
@mhansendev
mhansen.io
Reply all
Reply to author
Forward
0 new messages