2015-10-08 35 views
0

如何在Sequelize中關聯兩個表格?我試過belongsTo,但這不起作用。例如:如何通過ID關聯表格

第一個表:

users = sequelize.define('users', { 
id: { 
    type: Sequelize.INTEGER, 
    primaryKey: true, 
    autoIncrement: true 
}, 
name: Sequelize.TEXT, 
type: Sequelize.INTEGER 

二表:

profiles = sequelize.define('profiles', { 
id: { 
    type: Sequelize.INTEGER, 
    primaryKey: true, 
    autoIncrement: true 
}, 
place: Sequelize.TEXT, 
phone: Sequelize.INTEGER 

協會:

profiles.belongsTo(users, {foreignKey: 'id'}); 

請求:

users.findOne({ 
    where: {name: 'John'}, 
    include: [{model: db.tables.profiles}] 
}).then(function(user_data) { 
    console.log(user_data); 
}) 

返回[Error: profiles is not associated to users!]

我需要從表'profiles'中返回匹配的「users」行和具有相同id的行。錯誤在哪裏?

回答

1

您需要聲明兩個表的關聯。從你的模式我不能告訴連接條件是什麼。如果您的配置文件表中還有一列user_id,例如profiles.user_id = users.id,那麼您可以這樣說:

users.hasMany(profiles, { 
    foreignKey: 'id' 
}); 

profiles.belongsTo(users, { 
    foreignKey: 'user_id' 
});