0

I'm trying to get the total budgets of the last x days. I tried the following but the days without budgets are not being returned.

<?php

class Budget extends \Eloquent {

    public static function getTotalBudgetsByDay($days = 31)
    {
        $budgetByDays = self::where('created_at', '>=', \Carbon\Carbon::now()->subDays($days))
            ->groupBy('date')
            ->orderBy('date', 'ASC')
            ->get([
                \DB::raw('Date(created_at) as date'),
                \DB::raw('COUNT(*) as total')
            ]);

        return array_map(function ($row) {
            return $row->getAttributes();
        }, $budgetByDays->all());
    }

}

$budgetsByDays = \Budget::getTotalBudgetsByDay();

Result:

Array (
    [0] => Array
        (
            [date] => 2015-01-08
            [total] => 2
        )

    [1] => Array
        (
            [date] => 2015-01-09
            [total] => 1
        )

    [2] => Array
        (
            [date] => 2015-01-11
            [total] => 7
        )

)

in this case on 10 not appear in the array

Miguel Borges
  • 7,549
  • 8
  • 39
  • 57
  • I think you need only one row and no need to group by.It will produce 10 if you don't do group by – Shaiful Islam Jan 11 '15 at 18:19
  • Okay, and where would this '10' come from? Please show relevant data. – GolezTrol Jan 11 '15 at 18:19
  • @GolezTrol in table don't exists any budget created in day 10, that's why is not obtained. but I need to get it, and its total 0. – Miguel Borges Jan 11 '15 at 18:24
  • I don't know Eloquent that well, but I don't think it will solve this problem for you. It won't 'generate' missing data. I think the best solution would be to build an array with every data and a `total` of 0, and then merge those arrays. Anyway, you'd need some custom code for this. – GolezTrol Jan 11 '15 at 18:36
  • Read this http://stackoverflow.com/questions/3538858/mysql-how-to-fill-missing-dates-in-range – Jarek Tkaczyk Jan 11 '15 at 20:25

0 Answers0