Reputation: 427
i have 3 models, poll, category, and poll_to_category.
poll.server.model.js
module.exports = function(sequelize, DataTypes) {
var Poll = sequelize.define('Poll', {
poll_id:{type:DataTypes.INTEGER,primaryKey:true}
},
{
associate: function(models){
Poll.hasOne(models.Caetgory, {through:models.PollToCategory)
}
}
);
return Poll;
};
category.server.model.js
module.exports = function(sequelize, DataTypes) {
var Category = sequelize.define('Category', {
category_id:{type:DataTypes.INTEGER, primaryKey:true}
},
{
associate: function(models){
Category.hasMany(models.Poll, {through:models.PollToCategory)
}
}
);
return Category;
};
poll_to_category.server.model.js
module.exports = function(sequelize, DataTypes) {
var PollToCategory = sequelize.define('PollToCategory', {
ptc_id:{type:DataTypes.INTEGER,primaryKey:true},
poll_id:DataTypes.INTEGER,
category_id:DataTypes.INTEGER
},
{
associate: function(models){
PollToCategory.belongsTo(models.Poll, {foreignKey:'poll_id'}),
PollToCategory.belongsTo(models.Category, {foreignKey:'category_id'})
}
}
);
return PollToCategory;
};
when i try to query
db.Poll.findAll({include:db.Category}).then(function(polls,err){
if (err) return res.status(400).send({message: errorHandler.getErrorMessage(err)});
res.jsonp(polls);
});
i get the following error:
Possibly unhandled Error: ER_BAD_FIELD_ERROR: Unknown column 'category.poll_id' in 'field list'
i tried to play with the belongsTo / hasOne configuration between the 3 but either i get the above error, or i get no errors at all but i recieve the poll object with the attribute 'category' as 'null'. im new to sequelize.js, and im not sure on how to ask this question (terminology-wise).
how can i eager load the category to the poll, with regard to the above table structure?
Upvotes: 0
Views: 839
Reputation: 3597
I know I'm late to the party, but to clarify: you don't have 3 models. You have two models: Poll
and Category
. PollToCategory
is a belongsToMany
association between your two models.
Upvotes: 0
Reputation: 1122
You need to give a Alias to the third table name. Like this:
associate: function(models){
Poll.hasOne(models.Caetgory, {through:models.PollToCategory, as 'PollToCategory')
}
But the correct way is to let sequelize create the third entities. For this, you need to insert in associate the alias and set fixed 'through' name, then the sequelize create it for you.
Upvotes: 1