Jamie
Jamie

Reputation: 1014

Sequelize - multiple nested models with where clause

I have a model which has 2 associations, I want to return the model with both associations, but only where the criteria for one is met.

e.g.

        models.Users.findAll({
            include: [
                {
                    model: models.Context,
                    where: { id: req.session.contextObject.id }
                },
                {    
                    model: models.Role
                }
            ]
        }).then(function(fullUsers){...

So I want to return all Users, with their Contexts and Roles, but only where the Context matches a value I have.

Is is possible to return multiple associated models but with a where clause on one of the models?

This works absolutely fine when only including the Context model.

Upvotes: 0

Views: 1192

Answers (1)

demarchisd
demarchisd

Reputation: 732

If you want to filter by the Context's ID, you could use the Context's attribute reference on Users' model:

models.Users.findAll({
      where : { ContextId : req.session.contextObject.id }
    , include: [
        {
            model: models.Context           
        },
        {    
            model: models.Role
        }
    ]
}).then(function(fullUsers){...

Upvotes: 1

Related Questions