Skip to content

Instantly share code, notes, and snippets.

@erickhaendel
Created April 27, 2017 19:57
Show Gist options
  • Save erickhaendel/af1563aa254a1f37f72c4315b72617d4 to your computer and use it in GitHub Desktop.
Save erickhaendel/af1563aa254a1f37f72c4315b72617d4 to your computer and use it in GitHub Desktop.
User Model (file)
module.exports = function(sequelize, DataTypes){
var User = sequelize.define(
'User', {
name: {
type: DataTypes.STRING,
allowNull: false
}
},
{
classMethods:{
associate:function(models){
User.hasMany(models.Comment, { foreignKey: 'userId'} );
}
}
}
);
return User;
};
Comment Model (file):
module.exports = function(sequelize, DataTypes){
var Comment = sequelize.define(
'Comment', {
text: {
type: DataTypes.STRING,
allowNull: false
}
},
{
classMethods:{
associate:function(models){
Comment.belongsTo(models.User, { foreignKey:'userId'} );
}
}
}
);
return Comment;
};
You don't have to set the foreignkey, sequelize will handle it if you don't specify the foreignkeys.
Then in the query:
models.Comment.find({
where: { id: id },
include: [
models.User
],
limit: 1
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment