Search code examples
node.jssequelize.jssubquery

How to write nested queries using sequelize in nodejs


I'm trying to write nested queries using sequelize of this query.


const userIdPriorityLevel = await db.sequelize.query(
            `select "p_level" from roles  where id=(select "roleId" from users where id='${userId}');`
            , { raw: true });

the above query works like this

user table

id   roleId
1     2
2     3

roles table

id   p_level
2     4324
3     3423

please help how to do that.

updated:


        const userIdPriorityLevel = await db.Role.findAll({
            attributes: ['p_level'],
            include: [{
                model: db.User,
                required: true,
                attributes: [],
                where: {
                    id: userId
                }
            }
            ]
        })

        console.log("userid   ", userIdPriorityLevel)

when i print the above query it gives me this output

userid    [
  role {
    dataValues: { p_level: 700 },
    _previousDataValues: { p_level: 700 },
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      include: [Array],
      includeNames: [Array],
      includeMap: [Object],
      includeValidated: true,
      attributes: [Array],
      raw: true
    },
    isNewRecord: false
  }
]

i want to extract only this p_level: 700 value from above output. trying something like this

  const userPriorityLevel = userIdPriorityLevel[0][0]['p_level']

but it is not working.


Solution

  • Considering you also have Role.hasMany(User) association you can try something like this:

    const roles = await Roles.findAll({
      attributes: ['p_level'],
      include: [{
        model: User,
        required: true,
        attributes: [],
        where: {
          id: userId
        }
      }
      ]
    })
    

    Update: to get plain objects from Sequelize query call get({ plain: true }) for each model instance:

    const plainRoles = roles.map(x => x.get({ plain: true }))