如何通过sequelize在句子中使用db函数

时间:2018-05-28 03:41:25

标签: node.js database orm sequelize.js

我想找到本周和select dayofweek(datetime), avg(value) from Temperatures where week(datetime) = week(now()) group by dayofweek(datetime); 分组的平均值,所以我写了这个sql,sql运行良好,但我如何才能通过sequelize达到同样的目的。

Temperatures

这是我的 | field | type | |----------|-------------| | uuid | char(36) | | value | float | | datetime | datetime | 表: where

我已经阅读了续集的文档,但似乎没有明确解释如何在where: { [Sequelize.Op.eq]: [ sequelize.fn('week', Temperature.sequelize.fn('now')), sequelize.fn('week', Temperature.sequelize.col('datetime')), ] }, 句后使用函数,条件是函数而不是字段。

我已经尝试了,但它不起作用

import photo from "../img/reed.jpg";

const styles = {
  background: `url(${photo})`
};

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您可以使用sequelize.fn,例如:

[sequelize.fn('dayofweek', sequelize.col('datetime')), 'datetime']

有关详情 even when new blocks are created

答案 1 :(得分:0)

最后,我发现以下方法效果很好

return Temperature.findAll({
  attributes: [
    [Temperature.sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')), 'dayofweek'],
    [Temperature.sequelize.fn('AVG', Temperature.sequelize.col('value')), 'value'],
  ],
  where: sequelize.where(sequelize.fn('week', Temperature.sequelize.fn('now')), sequelize.fn('week', Temperature.sequelize.col('datetime'))),
  group: sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')),
});

如果我需要更多的条件过滤器,只需添加一个[Op.and]运算符

return Temperature.findAll({
  attributes: [
    [Temperature.sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')), 'dayofweek'],
    [Temperature.sequelize.fn('AVG', Temperature.sequelize.col('value')), 'value'],
  ],
  where: {
    [Sequelize.Op.and]: [
      sequelize.where(sequelize.fn('week', Temperature.sequelize.fn('now')), sequelize.fn('week', Temperature.sequelize.col('datetime'))),
    ]
  },
  group: sequelize.fn('dayofweek', Temperature.sequelize.col('datetime')),
});

这里是sql生成的

SELECT dayofweek(`datetime`) AS `dayofweek`, AVG(`value`) AS `value` FROM `Temperatures` AS `Temperature` WHERE (week(now())=week(`datetime`)) GROUP BY dayofweek(`datetime`);