Question

I have 2 modles candidate and role and role can have many candidates mapped to it in schema.

role.js

module.exports = function(sequelize, DataTypes) {
    var Role = sequelize.define('Role', {
        name: DataTypes.STRING,
        level: DataTypes.STRING,
        job_desc: DataTypes.STRING(500)
    },
    {
        associate: function(models) {
        Role.hasMany(models.Candidate);
        Role.hasMany(models.Requisition);
        }
    });

  return Role;
}

candidate.js

module.exports = function(sequelize, DataTypes) {
  var Candidate = sequelize.define('Candidate', {
    full_name: DataTypes.STRING,
    status: DataTypes.ENUM('REJECT', 'WAIT', 'HIRE')
  });

  return Candidate;
}

and while creating a candidate how can i map a role_id to a candidate in DB?

app.post('/candidate/create', function (req, res) {
    var passport = require('passport');
    passport.authenticate('basic');

    var roleid = req.param('role-level-id');
    var name = req.param('candidate-name');
    console.log("role-id: " + roleid);
    console.log("name: " + name);

    //
    var candidate_obj = db.Candidate.build({ full_name: name});
    candidate_obj.save().success(
        function(candidate) {
            console.log("obj created.");
            res.redirect('/candidates');
        }).error(function (error) {
            console.log(error);
            res.redirect('/candidate/create');
        });
});
Was it helpful?

Solution

Sir, your association method is totally different from documented: http://sequelizejs.com/docs/latest/associations

So, if you want to run with associations I can recommend you to follow the instructions.

  1. The first thing is to split models definitions and establishing associations, since to make association you need all the models to be defined already. If you trying to define association in the same file, where model defined – you might fall in error when one of associated model is not defined yet.

  2. If your model definition is written in db.Candidate variable you should to use exactly this variable name when establishing association. And to make associated models be well retrieved (or saved) on beautiful automatically created methods, you need to use parameter as while defining. dbCandidate.hasOne( db.Role, {as: 'Role'} )

  3. Any model associations are bidirectional. It mean you have to define not only db.Role.hasMany( db.Candidate, {as: 'Candidate'} but db.Candidate.hasOne( db.Role, {as: 'Role'} ) aslo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top