Search code examples
sequelize.jshas-and-belongs-to-many

Sequelize query belongstomany not including child attributes


I´m new to sequelize and trying to determine how to perform a query on a belongstomany relationship, where I need to check for the existence of the child relationship but I don´t want to bring any of its fields.

  Project.belongsToMany(models.User, {
        through: 'userproject', as: 'links', foreignKey: 'project_id', otherKey: 'user_id'
    });

My attempt:

  const linkedProjects = this.model.findAll({
        attributes: ['Project.*'],
        include: [{
            model: models.User,
            as: 'links',
            where: {
                userid: user.sub
            }
        }]
    });

However this stil brings me the projected links data, which is useless for me except for the where part.

What´s the best way to accomplish that without a "raw query" ? I´m looking for, basically:

select p.* from project p 
inner join userproject up on p.project_id = up.project_id 
inner join user u on up.user_id = u.id
where u.userid = 'xxx'

Solution

  • Re-iterating for marking it as a solution.

    The solution is to add attributes: [] to retrieve no columns in the sequelize operation. The attributes field is an array containing column names which have to be retrieved while executing the sequelize operation.

      const linkedProjects = this.model.findAll({
            attributes: ['Project.*'],
            include: [{
                model: models.User,
                as: 'links',
                attributes: [],
                where: {
                    userid: user.sub
                }
            }]
        });