【问题标题】:Multiple Sequelize Associations多个 Sequelize 关联
【发布时间】: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


【解决方案1】:

我最终更改了原始查询,因为当时我无法弄清楚。我最近偶然发现了同样的问题,并意识到问题来自我如何命名我的协会。我将transaction.hasMany 关联命名为transactions,最终将MySQL 与生成的查询混淆了,因为其中一个表名为事务。

TLDR,不要将您的关联命名为与您的任何表名相同的名称。

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多