sequelize:关联引用错误的foreignKey列名

时间:2017-03-26 06:38:20

标签: sequelize.js

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

所以这些表是这样的:blogs表通过accounts表上的外键accounts_idblogs表相关联,这似乎是一个简单的连接查询,但是我不能让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'

1 个答案:

答案 0 :(得分:2)

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

你可以试试,在两者中指出外包钥匙

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