代码之家  ›  专栏  ›  技术社区  ›  Muljayan

如何获取今天的sequelize js记录

  •  1
  • Muljayan  · 技术社区  · 7 年前

    我有一张桌子,看起来和下表很像。我想找出今天所有价格的总和。

    | id| price |       created        |
    |---|-------|----------------------|
    | 0 |  500  | 2018-04-02 11:40:48  |
    | 1 | 2000  | 2018-04-02 11:40:48  |
    | 2 | 4000  | 2018-07-02 11:40:48  |
    

    const TODAY = new Date();
    const SUM = await OrdersModel.sum('price', {
        where: {
          created: TODAY,
        },
    });
    console.log(SUM);
    

    const TODAY = new Date();
    const SUM = await OrdersModel.sum('price', {
        where: {
          created: Sequelize.DATE(TODAY),
        },
    });
    console.log(SUM);
    

    在终端上查询的SQL语句如下。

    执行(默认):选择sum(`price`)作为`sum`从`orders`作为`orders`其中`orders`.`created`='2019-05-27 18:30:00';

    1 回复  |  直到 7 年前
        1
  •  5
  •   Teocci    7 年前

    这里发生的事情是你在比较精确的时间戳,比如 '2019-05-27 11:40:48' '2019-05-27 18:30:00'

    const Op = Sequelize.Op;
    const TODAY_START = new Date().setHours(0, 0, 0, 0);
    const NOW = new Date();
    
    const SUM = await OrdersModel.sum('price', {
        where: {
          created: { 
            [Op.gt]: TODAY_START,
            [Op.lt]: NOW
          },
        },
     });
     console.log(SUM);
    

    您需要创建如下查询: created < [NOW] AND created > [TODAY_START] 为什么? NOW . 这段代码还将帮助您获得一系列日期的总和。

    请注意,PostgreSQL允许截断到特定的间隔。所以,你可以打电话给 sequelize.fn() read more in this link . 这样地:

    const SUM = await OrdersModel.sum('price', {
        where: {
          sequelize.fn('CURRENT_DATE'): {
            [Op.eq]:  sequelize.fn('date_trunc', 'day', sequelize.col('created'))
          }
        },
    });
    console.log(SUM);
    

    latest version

    npm i sequelize@5.8.6 --s
    
        2
  •  1
  •   Senthil    7 年前

    在不考虑时间的情况下添加日期函数进行日期比较

    const TODAY = new Date();
    const SUM = await OrdersModel.sum('price', {
        where: {
          sequelize.fn('CURRENT_DATE'): {$eq:  sequelize.fn('date_trunc', 'day', sequelize.col('created'))}
        },
    });
    console.log(SUM);
    
        3
  •  0
  •   Khalid Skiod    5 年前

    const moment = require('moment');
    const Op = require('sequelize').Op;
    const SUM = await OrdersModel.sum('price', {
        where : {
                    created_at : { [Op.gt] : moment().format('YYYY-MM-DD 00:00')},
                    created_at : { [Op.lte] : moment().format('YYYY-MM-DD 23:59')}
                },
    });
    console.log(SUM);
    
    推荐文章