Sequelize, Issue with filtering on the join model for belongsToMany associations

不羁的心 提交于 2019-12-11 01:59:19

问题


The Sequelize docs suggest that you can filter your query on join table attributes using the following params on the options object: [options.include[].through.where]

I've tried to use this formulation in the code below and found that the filtering does not work.

Model User and model Network are associated through the join table network-affiliations, which has additional attribute (boolean) 'confirmed'. I can't seem to write a query that returns only confirmed networks associated with a user.

My code is excerpted below.

const network_affiliations = db.define('network_affiliations', {
    networkEmail: { type: Sequelize.STRING },
    confirmed: { type: Sequelize.BOOLEAN }
}, {
    freezeTableName: true,
    defaultScope: {
        where: {
            confirmed: true
        }
    },
});

// User belongs to many Networks and Networks belong to many Users (join table)
User.belongsToMany(Network, { through: network_affiliations });
Network.belongsToMany(User, { through: network_affiliations });

//querying to find one user, including their confirmed networks
User.findOne({
            where: {
                email: req.body.email
            },
            include: [{ model: Network, through: { network_affiliations: { where: { confirmed: true } } } }]
        })

I expect this query to return a user instance with its associated networks -- but only networks where confirmed: true. Instead I'm getting all networks associated with the user (including confirmed: false and confirmed: undefined).

As you can also see in the above code, I tried setting a defaultScope for the join table ({confirmed: true}). This also appears not to do anything.

I've also tried a User.findAll query that is otherwise identical, and that also does not work.

What am I missing, or Sequelize just not working here?

Sequelize version: "^3.30.4"

来源:https://stackoverflow.com/questions/45685981/sequelize-issue-with-filtering-on-the-join-model-for-belongstomany-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!