【发布时间】:2018-08-31 14:50:12
【问题描述】:
当我想从引用的表中获取一些包含连接数据的记录时,Sequelize 会添加两次引用列:普通列和它们的副本,编写方式略有不同。
这是我的模型:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('result', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
test_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
references: {
model: 'test',
key: 'id'
}
},
item_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
references: {
model: 'item',
key: 'id'
}
},
}, // and many other fields
{
tableName: 'result',
timestamps: false, // disable the automatic adding of createdAt and updatedAt columns
underscored:true
});
}
在我的存储库中,我有一个方法,它通过连接数据获取结果。我定义了以下关联:
const Result = connection.import('../../models/storage/result');
const Item = connection.import('../../models/storage/item');
const Test = connection.import('../../models/storage/test');
Result.belongsTo(Test, {foreignKey: 'test_id'});
Test.hasOne(Result);
Result.belongsTo(Item, {foreignKey: 'item_id'});
Item.hasOne(Result);
// Defining includes for JOIN querys
var include = [{
model: Item,
attributes: ['id', 'header_en']
}, {
model: Test,
attributes: ['label']
}];
var getResult = function(id) {
return new Promise((resolve, reject) => { // pass result
Result.findOne({
where: { id : id },
include: include,
// attributes: ['id',
// 'test_id',
// 'item_id',
// 'result',
// 'validation'
// ]
}).then(result => {
resolve(result);
});
});
}
该函数产生以下查询:
SELECT `result`.`id`, `result`.`test_id`, `result`.`item_id`, `result`.`result`, `result`.`validation`, `result`.`testId`, `result`.`itemId`, `item`.`id` AS `item.id`, `item`.`title` AS `item.title`, `test`.`id` AS `test.id`, `test`.`label` AS `test.label` FROM `result` AS `result` LEFT OUTER JOIN `item` AS `item` ON `result`.`item_id` = `item`.`id` LEFT OUTER JOIN `test` AS `test` ON `result`.`test_id` = `test`.`id` WHERE `result`.`id` = '1';
注意它要从结果表中选择的额外 itemId、testId。我不知道这发生在哪里。这会产生:
Unhandled rejection SequelizeDatabaseError: Unknown column 'result.testId' in 'field list'
仅当我指定要选择的属性时才有效。
编辑:我在数据库中的表已经引用了其他具有 item_id 和 test_id 的表。那么是否不需要像我一样在应用程序代码中再次添加关联?
一个结果总是有一个项目和它所属的测试。
我该如何解决这个问题?
提前致谢,
迈克
【问题讨论】:
标签: node.js sequelize.js