Sequelize:关联引用了错误的ForeignKey列名 [英] sequelize: association is referencing to wrong foreignKey column name
本文介绍了Sequelize:关联引用了错误的ForeignKey列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以表是这样的: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:关联引用了错误的ForeignKey列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文