在Sequelize中使用连接表上的函数

时间:2015-07-28 14:31:36

标签: mysql node.js sequelize.js

我正在尝试在已连接表的列上运行TIMESTAMPDIFF()

现在,我正在使用它:

  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));

diff列已分组到Projects结果中,而不是Notes中的Projects结果。

例如,我期待这个:

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

但是,我得到了这个:

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

是否可以在联接表上运行函数?

1 个答案:

答案 0 :(得分:1)

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