Reputation: 568
I have two tables. How to link field in first table with id
field in second table in Sequelize? Example:
First table:
id | author | text
1 | 2 | 'test1'
2 | 2 | 'test2'
3 | 1 | 'test3'
Second table:
id | name
1 | John
2 | Jane
On request values from first table result should contain name in author
field. Example:
first.findAll().then(function(result) {
console.log(result);
});
Returns it:
id | author | text
1 | Jane | 'test1'
2 | Jane | 'test2'
3 | John | 'test3'
(Sorry for bad english)
Upvotes: 0
Views: 861
Reputation: 4373
You are looking for associations.
Your models will look something like this
'use strict';
module.exports = function(sequelize, DataTypes) {
var Table1 = sequelize.define('Table1', {
text: {
type:DataTypes.STRING
},
authorId: {
type: DataTypes.INTEGER,
references: "Table2",
referencesKey: "id",
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
Table1.belongsTo(models.Table2, { foreignKey: 'authorId' })
}
}
});
return Table1;
};
'use strict';
module.exports = function(sequelize, DataTypes) {
var Table2 = sequelize.define('Table2', {
name: {
type:DataTypes.STRING
}
}, {
classMethods: {
associate: function(models) {
Table2.hasMany(models.Table1, { foreignKey: 'authorId' })
}
}
});
return Table2;
};
And it seems like you want to eager load your authors.
Table1.findAll({
include:[
{ model: Table2 }
]
}).then(function(result){
console.log(result.get({plain:true})
})
Upvotes: 2