Reputation: 2017
I've got two tables that are structured like this:
FeedPost id, text, likecount, commentcount
Comment id, text, lkpfeedpostid
So there's a foreign key from comment to feedpost via lkpfeedpostid. So one FeedPost could have many Comment. I'm trying to set this up in sequalize so that when I do a FeedPost.findAll(), it pulls back the feed posts with all the comments.
Here's how I've set it up:
Model Definitions:
FeedPost:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('FeedPost', {
...
...
}, {
tableName: 'FeedPost',
classMethods: {
associate : function(models) {
FeedPost.hasMany( Comment, { as: 'comments' });
},
},
});
};
Comment:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Comment', {
...
...
}, {
tableName: 'Comment',
classMethods: {
associate : function(models) {
Comment.belongsTo(FeedPost, { foreignKey: 'lkpfeedpostid'})
},
},
});
};
I'm importing them like:
const FeedPost = sequelize.import('../models/FeedPost');
const Comment = sequelize.import('../models/Comment');
And passing them into an express router like:
app.use(feed(FeedPost, Comment));
module.exports = (FeedPost, Comment) => {
const api = Router();
api.get('/api/feed', (req, res) => {
FeedPost.findAll( { include: [ {model: Comment, as: 'Comment' }]}).then(results => {
res.json({results});
});
}
I've tried tons of variations of this found in these links:
http://docs.sequelizejs.com/manual/tutorial/models-definition.html#import
http://docs.sequelizejs.com/class/lib/associations/has-many.js~HasMany.html
And whenever I hit the route, I keep getting the error that says
Unhandled rejection SequelizeEagerLoadingError: Comment is not associated to Feed!
Upvotes: 0
Views: 154
Reputation: 545
I am going with that assumption that your sequelize version >=4.
classMethods
and instanceMethods
have been removed. The changelog can be found here : Sequelize V4 Breaking Changes
From their docs you can refer the current method to specify associations.
FeedPost
module.exports = function(sequelize, DataTypes) {
const FeedPost = sequelize.define('FeedPost', {/*Attributes here*/});
FeedPost.hasMany(Comment, { as: 'comments' })
};
Comment
module.exports = function(sequelize, DataTypes) {
const Comment = sequelize.define('Comment', {/*Attributes here*/});
Comment.BelongsTo(Comment, { foreignKey: 'lkpfeedpostid', targetKey: 'id' })
};
The following query should work:
FeedPost.findAll( { include: [ {model: Comment, as: 'comments' }]})
Upvotes: 2