【问题标题】:How can I combine 2 models in sequelize?如何在 sequelize 中组合 2 个模型?
【发布时间】:2022-02-18 03:33:17
【问题描述】:

我有 2 个模型,每个模型有 2 个主键(langId,topicCode)。 如何结合它们来选择值?

const field_A = {langId: {type:DataTypes.STRING, primaryKey: true}, topicCode: {type:DataTypes.STRING, primaryKey: true}, data:{type:DataTypes.STRING}}
const field_B = {langId: {type:DataTypes.STRING, primaryKey: true}, topicCode: {type:DataTypes.STRING, primaryKey: true}, storage:{type:DataTypes.STRING}}
Model_A.init(field_A, { timestamps:false, sequelize });
Model_B.init(field_B, { timestamps:false, sequelize });

如何使用模型之间的 sequelize 关联来执行以下操作?

SELECT * from Model_A, Model_B where Model_A.langId = Model_B.langId and Model_A.topicCode = Model_B.topicCode
[
{
  langId: 'xx',
  topicCode: 'yy',
  data: 'zz',
  storage: 'pp',
},
{
  langId: 'gg',
  ...
}
]

谢谢。
此致。

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    Sequelize 不支持关联中的复合键,因此您只需定义与其中一个键的关联,并且始终include 选项中指示on 选项以及两个字段的条件:

    联想

    modelA.belongsTo(modelB, { foreignKey: 'langId' });
    

    查询

    const modelAList = await ModelA.findAll({
      include: [{
        model: ModelB,
        on: {
          '$ModelA.langId$': Sequelize.col('ModelB.langId'),
          '$ModelA.topicCode$': Sequelize.col('ModelB.topicCode')
        }
      }]
    })
    

    【讨论】:

    • 感谢您的好意。我解决了这个问题如下。 ModelA.belongsTo(ModelB, {foreignKey: "langId", targetKey:'langId'}); ModelA.belongsTo(ModelB, {foreignKey: "topicCode", targetKey:"topicCode"}) 再次感谢您的及时回答,Anatoly。
    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    相关资源
    最近更新 更多