database - Sequelize 字段关联不起作用

标签 database node.js sequelize.js

我有两张 table 。如何将第一个表中的字段与 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.users 的作者姓名不是“作者”。我提出要求:
tables.comments.findAll({inclide: [{model: tables.users}]}).then(function(comments) {
    console.log(comments);
});

但结果字段 author 只有数字,而不是来自 users 的名称!
错误在哪里?

(抱歉英语不好)

最佳答案

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

对于您的评论表,它将是:

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

对于您的用户表,它将是:
tables.users.hasMany(tables.models.comments, {
  foreignKey: 'id'
});

关于database - Sequelize 字段关联不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854133/

相关文章:

node.js - 在 Elastic Beanstalk 上部署 KeystoneJS 时遇到问题

javascript - 如何在 findAll 上的 node.js Sequelize 中具有多个关联/条件/包含

javascript - Sequelize 和嵌套结果?

php - FileMaker:与 Magento 集成

database - 具有多个类别的ElasticSearch文档

node.js - MongoDB atomic "findOrCreate": findOne, 如果不存在则插入,但不更新

javascript - 在脚本中编写 ejs 给了我错误 'Expression expected'

node.js - SequelizeJS 无法读取未定义的属性 'getTableName'

database - ALL_TAB_MODIFICATIONS,但对于列

保存 JSON 对象的 JavaScript/Node.js 最佳实践和检索特定值的最有效方法