找不到让子查询与 sequelize 一起使用的方法,所以我使用了原始查询。我试图弄清楚在执行原始查询时如何从关联表中获取数据。这是我尝试过的,但它只返回主表中的数据,而关联表中不返回任何数据:
const rawQuery = `select * from (
select distinct on ("patientId") *
from public."Billings"
order by "patientId","createdAt" desc) as "recentPatientBilling"
where balance > 0;`;
const debtors = await sequelize.query(
rawQuery,
{
model: Billing,
mapToModel: true,
nest: true,
raw: true,
include: [{
model: Patient, attributes: ['id']
}]
}
);
该协会是:Billing.associate = function(models) {
Billing.belongsTo(models.User, {
foreignKey: 'employeeId',
as: 'employee'
});
Billing.belongsTo(models.Patient, {
foreignKey: 'patientId',
as: 'patient'
});
};
关于如何让这个工作的任何想法? (已编辑)
最佳答案
您是否尝试将 {as:'patient'} 放入 include 语句中?
include: [{
model: Patient,
as:'patient',
attributes: ['id']
}]
关于postgresql - 如何从 Sequelize 中的关联表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65073725/