Kin
Kin

Reputation: 4596

Is it possible add extra field in Sequelize relation?

I have belongsTo relation like this:

classMethods: {
    associate: function(models) {
        User.belongsTo(models.Prefs, {timestamps: false, foreignKey: 'Type', targetKey: 'UserType'})

    }
}

which produces

 LEFT OUTER JOIN `prefs` AS `Prefs` ON `User`.`Type` = `Prefs`.`UserType`

The problem is that I also need to add extra check like

AND `Prefs`.`Section` = 'GLOBAL'

Is it possible?

Upvotes: 0

Views: 962

Answers (1)

piotrbienias
piotrbienias

Reputation: 7411

I believe this is duplicate of Sequelize - Join with multiple column .

You need to use custom ON condition in the JOIN clause

User.findAll({
    include: [
        {
            model: Prefs,
            on: {
                Type: db.sequelize.where(db.sequelize.col("User.Type"), "=", db.sequelize.col("Prefs.UserType")),
                Section: 'GLOBAL'
            },
            attributes: [] // do not return any columns of Prefs table
        }
    ]
}).then((users) => {
    // resulting users...
});

EDIT

I believe scope is what you are looking for. Try adding it to the association

classMethods: {
    associate: function(models) {
        User.belongsTo(
            models.Prefs,
            {
                timestamps: false,
                foreignKey: 'Type',
                targetKey: 'UserType',
                scope: { Section: 'GLOBAL' }
            }
        );
    }    
}

Upvotes: 1

Related Questions