Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: find latest record per group of id

I'm trying to accomplish the same query on the link below but got no luck here:

https://dzone.com/articles/get-last-record-in-each-mysql-group

Can you suggest the proper way of converting the raw query on the link above into sequelize ORM format?

like image 697
Nestor A Avatar asked Jan 30 '18 05:01

Nestor A


2 Answers

The idea would be something like this:

Posts.findAll({
    attributes: [sequelize.fn("max", sequelize.col('id'))],
    group: ["category_id"]
}).then(function(maxIds){
    return Posts.findAll({
        where: {
            id: {
                [Op.in]: maxIds
            }
        }
    })
}).then(function(result){
    return Promise.resolve(result);
});
like image 134
My Nguyen Avatar answered Oct 09 '22 19:10

My Nguyen


Here's what I did base on Nguyen's idea with some tweaks:

  let conversationIds = conversations.map(conversation => {
    return conversation.conversation_id;
  });

  models.conversationDetails.findAll({
    attributes: [
      [models.sequelize.fn("max", models.sequelize.col('id')), 'id']
    ],
    where: {
      conversation_id: conversationIds
    },
    group: ['conversation_id']
  })
  .then(function(results) {
    let ids = results.map(result => {
      return result.id;
    });

    models.conversationDetails.findAll({
      include: [
        {
          model: models.conversationMeta,
          as: 'conversationMeta'
        }
      ],
      where: {
        id: {
            [Op.in]: ids
        }
      }
    })
    .then(function(conversationList) {
      callback(false, conversationList);
    })
    .catch(function(error) {
      console.log(error);
      callback(true, 'Internal Server Error');
    });
  })
  .catch(function(error) {
    console.log(error);
    callback(true, 'Internal Server Error');
  });
like image 36
Nestor A Avatar answered Oct 09 '22 21:10

Nestor A