【问题标题】:Getting the sum of field with where conditions with Eloquent使用 Eloquent 获取 where 条件的字段总和
【发布时间】:2013-12-01 03:24:30
【问题描述】:

我正在尝试获取所有时间和过去 24 小时内下载文件的总数,以用于报告目的。我正在处理的表有一个downloaded_at 字段,它是一个DATETIME 类型和一个size 字段,它是以字节为单位的文件大小。在我的模型中,我正在执行以下查询:

return array(
    'totalBandwidth' => self::where('downloaded_at', 'IS NOT', DB::raw('null'))->sum('size'),
    'bandwidthLast24Hours' => self::where('downloaded_at', 'IS NOT', DB::raw('null'))->where('downloaded_at', '>' , new DateTime('yesterday'))->sum('size')
);

很简单,但是这两个查询都返回NULL,我不知道为什么。我几乎根据 SO 和 Laravel 论坛上的答案编写了这些查询。

【问题讨论】:

  • 您是否在查询结束时错过了->get()

标签: mysql sql laravel-4 eloquent


【解决方案1】:

那是因为你不能像那样检查IS NOT NULL。你必须使用whereNotNull 方法。示例:

return array(
    'totalBandwidth' => self::whereNotNull('downloaded_at')->sum('size'),
    'bandwidthLast24Hours' => self::whereNotNull('downloaded_at')->where('downloaded_at', '>', new DateTime('yesterday')->sum('size')
);

【讨论】:

    【解决方案2】:

    where函数中可用的运算符与query builder one's相同:

    protected $operators = array(
        '=', '<', '>', '<=', '>=', '<>', '!=',
        'like', 'not like', 'between', 'ilike',
        '&', '|', '^', '<<', '>>',
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多