StormyTalent
StormyTalent

Reputation: 227

How can I combine 2 models in sequelize?

I have 2 models, each model has 2 primary keys(langId, topicCode). How can I combine them to select the value?

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 });

How can I perform the action as followings by using sequelize associations between models?

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',
  ...
}
]

Thank you.
Best regards.

Upvotes: 0

Views: 1036

Answers (1)

Anatoly
Anatoly

Reputation: 22758

Sequelize does not support composite keys in associations so you need to define associations with only one of keys and always indicate the on option in include option with conditions for both fields:

association

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

query

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

Upvotes: 1

Related Questions