sequelize.js - Sequelize : association is referencing to wrong foreignKey column name

标签 sequelize.js

我在这个问题上苦苦挣扎了几个小时,我似乎找不到解决这个令人困惑的错误的方法。我正在尝试使用连接表进行查询并使用嵌套对象显示结果。

所以表是这样的:blogs 表通过 blogs 上的外键 accounts_id 关联到 accounts 表> 表,这似乎是一个简单的连接查询,但我不能让 sequelize 使用正确的外键列名,因为它认为外键被称为 account_id

模型是这样定义的:

账户:

module.exports = function(sequelize, DataTypes) {
    return sequelize.define('accounts', {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        username: {
            type: DataTypes.STRING,
            allowNull: false
        },
        ............
    }, {
        tableName: 'accounts',
        timestamps: false,
        freezeTableName: true
    });

博客:

module.exports = function(sequelize, DataTypes){
    var model = sequelize.define("blogs", {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        title: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        content: {
            type: DataTypes.STRING,
            allowNull: false
        },
        accounts_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
        },
        ............
    }, {
        tableName: "blogs",
        timestamps: false,
        underscored: true
    });

    model.belongsTo(sequelize.models.accounts);
    sequelize.models.accounts.hasMany(model, {targetKey: "accounts_id"});

    return model;
};

查询是这样的:

var criteria = {
    include: [$db.models.accounts]
};

return model.findAll(criteria);

但它会抛出 Error: ER_BAD_FIELD_ERROR: Unknown column 'blogs.account_id' in 'field list'

最佳答案

有很多不支持目标键选项 https://github.com/sequelize/sequelize/issues/4258

你能试试吗,在两者中都点外键

    model.belongsTo(sequelize.models.accounts, {foreignKey: "accounts_id"});
    sequelize.models.accounts.hasMany(model, {foreignKey: "accounts_id"});

关于sequelize.js - Sequelize : association is referencing to wrong foreignKey column name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025861/

相关文章:

javascript - 如何使用 Discord.JS DM 某些用户?

node.js - Sequelize @6.3.4 无法连接到 docker -> postgres

arrays - 如何使用 LIKE 运算符在数组中搜索

javascript - 如何在 Node.js 网站中组织模型?

javascript - sequelize 上的多个外键(一对多或多对多)?

orm - GraphQL, Dataloader, [ORM 与否], 有很多关系理解

node.js - 来自关联 fooInstance.getBars() 的 sequelize 方法返回错误值

javascript - 我的邮寄路线有问题吗?

node.js - .findall() 在模型中应用 where 条件后给出一切

sql - 在 Sequelize 中同时查询两个组合字段