Reputation: 568
How can I associate two tables in Sequelize? I tried belongsTo
, but this doesn't work. Example:
First table:
users = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.TEXT,
type: Sequelize.INTEGER
Second table:
profiles = sequelize.define('profiles', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
place: Sequelize.TEXT,
phone: Sequelize.INTEGER
Association:
profiles.belongsTo(users, {foreignKey: 'id'});
Request:
users.findOne({
where: {name: 'John'},
include: [{model: db.tables.profiles}]
}).then(function(user_data) {
console.log(user_data);
})
Returned [Error: profiles is not associated to users!]
I need to return the matched line of "users" and the line with the same id from the table 'profiles'. Where is the mistake?
Upvotes: 0
Views: 58
Reputation: 9418
You need to declare the association for both tables. From your schema I can't tell what the join condition is. If your profiles table also has a column user_id
such that profiles.user_id = users.id
, then you could say the following:
users.hasMany(profiles, {
foreignKey: 'id'
});
profiles.belongsTo(users, {
foreignKey: 'user_id'
});
Upvotes: 1