Created
April 27, 2017 19:57
-
-
Save erickhaendel/af1563aa254a1f37f72c4315b72617d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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