如何在Sequelize中关联两个表?我试过belongsTo
,但这不起作用。例如:
第一张表:
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!]
我需要返回"用户"的匹配行。以及表格'中具有相同ID的行。错误在哪里?
答案 0 :(得分:1)
您需要声明两个表的关联。从您的架构我不知道连接条件是什么。如果您的个人资料表格还有user_id
列profiles.user_id = users.id
,那么您可以说出以下内容:
users.hasMany(profiles, {
foreignKey: 'id'
});
profiles.belongsTo(users, {
foreignKey: 'user_id'
});