Mrugesh
Mrugesh

Reputation: 4517

sequelize.fn distinct value does not give all the columns for the criteria

My query is as shown below:

db.orderUser.findAll({
                where: {partner_id: req.user.id},
                attributes: [
                    [Sequelize.fn('DISTINCT', Sequelize.col('user_email')), 'user_email'],
                ]
            }).then((info) => {
                response.sendsuccessData(res, 'Your user contact list', info);
            })

In the result, I only get user_email column. So is there a way to get all the column for the criteria?

Upvotes: 1

Views: 8632

Answers (1)

AbhinavD
AbhinavD

Reputation: 7282

You can concat the values by obtaining it from the Model.rawAttributes

const User = sequelize.define('User', {
  username: Sequelize.STRING,
  name: Sequelize.STRING
});

sequelize.sync({ force: true })
  .then(() => {
    User.create({
      username: 'test123',
      name: 'test'
    })
      .then(() => {
        User.findAll({
          attributes: [
            [Sequelize.fn('DISTINCT', Sequelize.col('username')), 'username'],
          ].concat(Object.keys(User.rawAttributes)),
        }).then((res) => {
          console.log(res);
        });
      });
  });

Upvotes: 2

Related Questions