如何通过sequelize在where语句中使用db函数
Posted
技术标签:
【中文标题】如何通过sequelize在where语句中使用db函数【英文标题】:how to using a db function in where sentence via sequelize 【发布时间】:2018-05-28 03:41:24 【问题描述】:我想求本周的平均值并按dayofweek
分组,所以我写了这个sql,sql运行良好,但是如何通过sequelize达到同样的目的。
select dayofweek(datetime), avg(value) from Temperatures where week(datetime) = week(now()) group by dayofweek(datetime);
这是我的Temperatures
表:
| field | type |
|----------|-------------|
| uuid | char(36) |
| value | float |
| datetime | datetime |
我看过sequelize的文档,但是where
这句话后面好像没有明确说明如何使用函数,条件是函数而不是字段。
我已经试过了,但是不行
where:
[Sequelize.Op.eq]: [
sequelize.fn('week', Temperature.sequelize.fn('now')),
sequelize.fn('week', Temperature.sequelize.col('datetime')),
]
,
感谢您的帮助!
【问题讨论】:
【参考方案1】:您可以为此使用sequelize.fn
,如下所示:
[sequelize.fn('dayofweek', sequelize.col('datetime')), 'datetime']
更多详情DO READ
【讨论】:
感谢您的帮助!where
是一个对象,我必须将它与 [Sequelize.Op.and] 运算符一起使用。
检查这个,你会得到更好的主意:***.com/questions/50553568/…【参考方案2】:
最后,我发现下面的方法效果很好
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`);
【讨论】:
以上是关于如何通过sequelize在where语句中使用db函数的主要内容,如果未能解决你的问题,请参考以下文章
在 sequelize 中使用 findByPk 和 WHERE 条件