2015-09-29 65 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' 
});