2015-09-29 40 views
0

我有两个表。如何将第一个表中的字段与Sequelize的第二个表中的id字段链接起来?续集字段关联不起作用

第一个表:

tables.comments = sequelize.define('comments', { 
    id: { 
     type: Sequelize.INTEGER, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    text: Sequelize.TEXT, 
    article: Sequelize.INTEGER, 
    author: { 
     type: Sequelize.INTEGER, 
     references: "users", 
     referencesKey: "id", 
     allowNull: false 
    }, 
    answer: Sequelize.INTEGER, 
    rating: { 
     type: Sequelize.INTEGER, 
     defaultValue: 0 
    } 
}, { 
    classMethods: { 
     associate: function(models) { 
      tables.comments.belongsTo(tables.models.users, {foreignKey: 'author', targetKey: 'name'}); 
     } 
    } 
}); 

二表:

tables.users = sequelize.define('users', { 
    id: { 
     type: Sequelize.INTEGER, 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    mail: Sequelize.TEXT, 
    name: Sequelize.TEXT, 
    pass: Sequelize.TEXT, 
    status: { 
     type: Sequelize.INTEGER, 
     defaultValue: 0 
    }, 
    rating: { 
     type: Sequelize.INTEGER, 
     defaultValue: 0 
    }, 
    ban: { 
     type: Sequelize.INTEGER, 
     defaultValue: 0 
    }, 
    key: Sequelize.TEXT 
}, { 
    classMethods: { 
     associate: function(models) { 
      tables.users.hasMany(tables.models.comments, {foreignKey: 'author'}); 
     } 
    } 
}); 

我需要得到tables.comments,但如果不是“作者”将是表的作者的名字。用户。我提出要求:

tables.comments.findAll({inclide: [{model: tables.users}]}).then(function(comments) { 
    console.log(comments); 
}); 

但在领域结果author只数,而不是从users的名字! 错误在哪里?

(对不起,我英文不好)

回答

1

在联营类方法,你要使用的类方法中定义的表的列名。我假设连接条件是comments.author = users.id

您的意见表,这将是:

tables.comments.belongsTo(tables.models.users, { 
    foreignKey: 'author' 
}); 

为您的用户表,这将是:

tables.users.hasMany(tables.models.comments, { 
    foreignKey: 'id' 
});