user499054
user499054

Reputation:

Using function on joined table in Sequelize

I'm trying to run TIMESTAMPDIFF() on a column of a joined table.

Right now, I am using this:

  Project
    .findAll({
      include: [Note, Link],
      attributes: [
        [sequelize.fn('TIMESTAMPDIFF', sequelize.literal('SECOND'), sequelize.literal('CURRENT_TIMESTAMP'), sequelize.col('notes.createdAt')), 'diff']
      ]
    })
    .then(res.send.bind(res));

But the diff column is grouped into the Projects result, not the Notes result within the Projects.

For example, I am expecting this:

[
   {id: 1, name: "Some Project", notes: [id: 33, diff: 123] },
   {id: 2, name: "Another Project", notes: [id: 34, diff: 456] }     
]

But, I am getting this:

[
   {id: 1, name: "Some Project", diff: 123, notes: [id: 33] },
   {id: 2, name: "Another Project", diff: 456, notes: [id: 34] }    
]

Is it possible to run functions on the joined table?

Upvotes: 0

Views: 263

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28798

Project
.findAll({
  include: [{
    model: Note,
    attributes: [[sequelize.fn('TIMESTAMPDIFF', sequelize.literal('SECOND'), sequelize.literal('CURRENT_TIMESTAMP'), sequelize.col('notes.createdAt')), 'diff']
  }, Link]
})

Upvotes: 2

Related Questions