Marc
Marc

Reputation: 7022

Sequelize: Filter by association without including associated data

All of the examples I have seen, including the documentation suggest that filtering by association should use the following syntax

[contrived exampled]
User.findAndCountAll({
    include: [
        {
            model: models.Task,
            as: 'tasks',
            where: {
                status: 'complete'
            },
        },
    ],
})

But this style will include completed tasks. What if you want to filter by association without including the associated records? I'm not talking about ex post facto using toJSON. but at query level.

Upvotes: 2

Views: 1997

Answers (1)

KenOn10
KenOn10

Reputation: 1968

a) If you want to see Users having at least one task, you can remove the (optional) WHERE clause. b) You can suppress the Task attributes, if you don't need them (shown below).

   User.findAndCountAll({
       include: [
          {
          model: models.Task,
          required : true,      // INNER JOIN....
          attributes: []        // no task fields shown in result...
          }
       ]
   );

Upvotes: 3

Related Questions