首页 > 解决方案 > 如何从sequelize中的关联表中获取数据

问题描述

找不到让子查询与 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'
    });
  };

关于如何让这个工作的任何想法?(已编辑)

标签: postgresqlsequelize.js

解决方案


您是否尝试将 {as:'patient'} 放在包含语句中?

 include: [{
        model: Patient, 
        as:'patient',
      attributes: ['id']
      }]

推荐阅读