【问题标题】:sequelize: association is referencing to wrong foreignKey column namesequelize:关联引用了错误的 foreignKey 列名
【发布时间】:2017-08-18 22:44:59
【问题描述】:

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

所以表是这样的: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'

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

    您必须同时设置hasMany({ sourceKeybelongsTo({ targetKey

    从 sequelize 6.14.0 开始,要获取自定义连接列,您应该执行以下操作:

    const Country = sequelize.define('Country', {
      country_name: { type: DataTypes.STRING, unique: true },
    });
    const City = sequelize.define('City', {
      parent_country: { type: DataTypes.STRING },
      city_name: { type: DataTypes.STRING },
    });
    Country.hasMany(City, { foreignKey: 'parent_country', sourceKey: 'country_name' } )
    City.belongsTo(Country, { foreignKey: 'parent_country', targetKey: 'country_name' } )
    

    完整的可运行示例位于:Sequelize targetKey not working

    【讨论】:

    【解决方案2】:

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

    你可以试试,在两个中都指向foregin键

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-11
      • 2023-03-11
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2019-10-01
      相关资源
      最近更新 更多