【发布时间】:2021-06-22 01:49:22
【问题描述】:
我在模型之间有一些关联,如下所示:
Patient.hasMany(Transaction, {
as: 'transactions',
foreignKey: 'patient_id',
sourceKey: 'id'
});
Transaction.belongsTo(Patient, {
as: 'patient',
foreignKey: 'patient_id',
targetKey: 'id'
});
Transaction.hasMany(Transaction, {
as: 'transactions',
foreignKey: 'item_to_pay',
sourceKey: 'id'
});
我正在编写一个查询来获取属于患者的交易列表,并包括与之关联的模型:
Transaction.findAll({
where: {
patient_id: 1
},
include: [{
model: Patient,
as: 'patient',
attributes: ['first_name']
}, {
model: Transaction,
as: 'transactions',
include: [{
model: Patient,
as: 'patient',
attributes: ['first_name']
}]
}],
});
但是,当结果返回时,它并没有像我预期的那样包含第二个嵌套患者模型。
我也试过写一个不同的查询来看看我是否能得到想要的结果:
Transaction.findAll({
where: {
patient_id: 1
},
include: [{
model: Transaction,
as: 'transactions',
include: [{
model: Patient,
as: 'patient',
attributes: ['first_name']
}]
}],
});
但此查询出错并返回“字段列表中的未知列 '患者.id'”。
有人发现我的查询或关联有问题吗?关于这里的关联,我有什么不明白的地方吗?
【问题讨论】:
-
尝试将
id属性添加到attributes: ['first_name'] -
感谢您的建议,但得到了相同的结果。
-
尝试在根选项中添加
subQuery: false。
标签: node.js sequelize.js