Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize, problem getting associations to return

I'm currently experimenting with Sequelize and have two objects, a Person and Position, When getting a list of persons I want to get their position.

models:

var User = sequelize.define('user', {
    first_name: Sequelize.STRING,
    last_name: Sequelize.STRING 
});

var Position = sequelize.define('position', {
    name: Sequelize.STRING,
    affiliation: Sequelize.STRING
});

Position.hasMany(User, { foreignKey : 'position_id' });
User.belongsTo(Position, { foreignKey : 'position_id'});

My query:

User.findAll({ fetchAssociations: true }, function(results) {
    //I've tried doing some work in here, but haven't found the correct procedure. 
}).on('success', function(results) {
    res.render('users', {
        title: 'user page',
        users: results
    });
});

Watching the log it never queries Person at all. Do I need to use queryChaining? From the documentation I was able to find it appeared it should auto fetch associations.

like image 743
Jeremy B. Avatar asked Jun 15 '11 14:06

Jeremy B.


1 Answers

From April 2013 in v1.7.0 you need just to expand your Associations to:

Position.hasMany(User, {foreignKey : 'position_id', as: 'User'});
User.belongsTo(Position, {foreignKey : 'position_id', as: 'Posit'});

and then find all Users with associated Positions

User.findAll({
      include: [{
        model: Position, as: 'Posit'
      }]
}).success(function(match) {
    // your logic
});
like image 51
khex Avatar answered Oct 25 '22 13:10

khex