Sequelize: Connect two tables on composite keys
I have troubles figuring out, how to connect two tables on the composite keys. I will note the example that work for me here. Just so I can remember it in the future, since I will most likely come across this problems again.
I will use Heros and Summons as example here, simply because it was a work example, and I am not sure, how much am I allowed to share.
I have associated the models with the:
Summons.hasMany(models.Heros) Heros.belongsTo(models.Summons);
And here is the final snippet:
models.Heros .findAll({ include: [{ model: models.Summons, on: { '$hero.first_name$': {[Sequelize.Op.col]: summon.first_name}, '$hero.last_name$': {[Sequelize.Op.col]: summon.last_name}, }, }, }], attributes: { exclude: ['assumedIdField'] }, })
So things to keep in the account:
- The variables associated need to be inside the $$ signs
- The entire chain needs to be there, putting just a column name does not work
- The automatically created ID needs to be filtered out from the results, since it (most likely) does not exist in the tables