many to many - Sequelize belongsToMany -
i have used sequelize , setup many-to-many relationship using belongstomany()
. however, when query out data, this:
api.models.operator.find({ where: { id: connection.params.id }, include: [ { model: api.models.permission, include: [ { model: api.models.activity } ] } ] })
i activity not associated permission!
error. why? doesn't fact belongstomany connects activity through permission operator imply association?
my permission model:
module.exports = function(sequelize, datatypes) { return sequelize.define("permission", { id: { type: datatypes.bigint, allownull: false, primarykey: true, autoincrement: true }, operator_id: { type: datatypes.bigint, allownull: false, references: 'operator', referenceskey: 'id', comment: "the operator in permission." }, activity_id: { type: datatypes.bigint, allownull: false, references: 'activity', referenceskey: 'id', comment: "the activity in permission." }, createdat: { type: datatypes.date, allownull: false, defaultvalue: datatypes.now, comment: "date of record creation." }, updatedat: { type: datatypes.date, allownull: false, defaultvalue: datatypes.now, comment: "date of last record update." }, deletedat: { type: datatypes.date, comment: "date record marked deleted." } }, { comment: "a permission indicates allowed activity operator, ex: superadmin allowed 'post /workorders'.", classmethods: { associate: function(models) { models.operator.belongstomany(models.activity, {through: models.permission, foreignkey: 'operator_id', ondelete: 'cascade', onupdate: 'cascade'}); models.activity.belongstomany(models.operator, {through: models.permission, foreignkey: 'activity_id', ondelete: 'cascade', onupdate: 'cascade'}); } } } ); }
which myself resolved follows:
modela.belongstomany(modelb, { through: 'modelc', foreignkey: 'modelaid' });
you call:
modela.findall({ include: [{ model: modelb }]}).then(function(success) {}, function(error) {});
if want using:
modelb.findall({ include: [{ model: modela }]}).then(function(success) {}, function(error) {});
you must declared
modelb.belongstomany(modela, { through: 'modelc', foreignkey: 'modelbid' });
^^ luck u!!!! ^^.