0

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.

4
  • What exactly do you want? Rewrite this plain SQL query to a Sequelize one? Or just correct it somehow? Commented Jan 27, 2022 at 14:40
  • Rewrite this plain SQL query to a Sequelize one Commented Jan 28, 2022 at 7:11
  • Did you already define Sequelize models and associations? Commented Jan 28, 2022 at 9:18
  • yes, i did this User.belongsTo(Role) where user and role both are tables. Commented Feb 1, 2022 at 10:02

1 Answer 1

1

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 }))
Sign up to request clarification or add additional context in comments.

2 Comments

it works, thanks. but when i want the p_level value from its output, please check my updated question.
see updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.