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

Laravel Group By如果没有行,则返回零

  •  0
  • Nevermore  · 技术社区  · 6 年前

    我列出了过去16天的浏览量。我想写0;如果日期没有行:

    $digital_case_daily_views = DB::table('digital_case_views')
    ->select(DB::raw('count(*) as numOfDigitalCaseViews'))->groupBy('created_at')
    ->orderBy('created_at', 'desc')->limit(16)->get();
    

    拉拉维尔5.6

    它的回报是:

        "digital_case_daily_views": [
            {
                "numOfDigitalCaseViews": 162
            },
            {
                "numOfDigitalCaseViews": 458
            },
            {
                "numOfDigitalCaseViews": 287
            },
            {
                "numOfDigitalCaseViews": 1
            },
            {
                "numOfDigitalCaseViews": 1
            },
            {
                "numOfDigitalCaseViews": 1
            }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Grey    6 年前

    从数据库中获取的行数不能超过可用的行数,如果您希望在剩余的天数内拥有0行,则必须将它们添加到数组中,我已经为您编写了一个函数,可以帮助您完成以下操作:

    class Foo {
        static public function addRemainingDays(array $arr, int $amount) {
            if(count($arr) === $amount) {
                return $arr;
            }
    
            for($i = 0; i > $amount - count($arr); i++) {
                array_push($arr, (object)["numOfDigitalCaseViews" => 0]);
            }
    
            return $arr
        }
    }