Reputation: 2240
I have defined two models and HasMany relationship between Users and Teams. My final code is like this:
app.listen(3000, function () {
sequelize = new Sequelize('mysql://username:password@localhost:3306/restful_api_demo');
sequelize
.authenticate()
.then(function (err) {
console.log('Connection has been established successfully.');
User = sequelize.define('users', {
firstName: { type: Sequelize.STRING },
lastName: { type: Sequelize.STRING }
});
Team = sequelize.define('teams', {
teamName: { type: Sequelize.STRING },
projectName: { type: Sequelize.STRING }
});
Team.hasMany(User, { foreignKey: 'teamId' });
//get all model names into an array
var modelObj = sequelize.models;
for (var key in modelObj) {
var value = modelObj[key];
models.push(value);
}
models.forEach(function (m) {
// Read the model name
var modelName = m.getTableName();
var assotions = m.associations;
for (key in assotions) {
var assotionType = assotions[key].associationType;
var assoModel = sequelize.model(key);
app.get('/' + modelName + '/:id/' + key, function (req, res) {
var id = req.params.id;
assoModel.findAll(
{
where: { teamId: id }
}).then(function (i) {
res.json(i);
});
});
}
})
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
});
It gives below json result from this URL. http://localhost:3000/teams/1/users
[
{
"id": 1,
"firstName": "John1",
"lastName": "Hancock1",
"createdAt": "2017-01-12T07:06:53.000Z",
"updatedAt": "2017-01-12T07:06:53.000Z",
"teamId": 1
},
{
"id": 2,
"firstName": "John2",
"lastName": "Hancock2",
"createdAt": "2017-01-12T07:18:48.000Z",
"updatedAt": "2017-01-12T07:18:48.000Z",
"teamId": 1
}
]
I modified the code for get foreign key to the query.
var foreign = assotions[key].foreignKey;
var assoModel = sequelize.model(key);
app.get('/' + modelName + '/:id/' + key, function (req, res) {
var id = req.params.id;
assoModel.findAll({
where: {foreign: id}
}).then(function (i) {
res.json(i);
});
});
It gives this error.
Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'users.foreign' in 'where clause'
How can I get the value of this variable to the query instead of variable name?
Upvotes: 0
Views: 1975
Reputation: 184
The associations have 'associationType' method but also has foreignKey method
...
var foreign = assotions[key].foreignKey;
var query = {
[foreign]: id // value you want
}
...
assoModel.findAll({
where: query
}).then(function (i) {
res.json(i);
});
Upvotes: 2