如何通过id关联表

How to associate tables via id

如何在 Sequelize 中关联两个 table?我试过 belongsTo,但这不起作用。示例:

第一个table:

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

第二个table:

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!]

我需要 return "users" 的匹配行和 table 'profiles' 中具有相同 ID 的行。哪里错了?

您需要为两个 table 声明关联。从您的架构中我无法判断连接条件是什么。如果您的配置文件 table 也有一个列 user_id 使得 profiles.user_id = users.id,那么您可以说以下内容:

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

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