【问题标题】:How to associate tables via id如何通过 id 关联表
【发布时间】:2015-10-09 02:04:49
【问题描述】:

如何在 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!]

我需要从表'profiles'中返回匹配的“users”行和具有相同id的行。哪里错了?

【问题讨论】:

    标签: database node.js sequelize.js


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多