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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With