mercredi 27 avril 2016

Laravel count results on specific date and column

In my database I am having the following records:

id    code   product_amount         created_at
 1    ORD-1      250          2016-04-04 05:15:05 PM
 2    ORD-1      150          2016-04-04 05:15:05 PM
 3    ORD-2      450          2016-04-05 11:18:17 PM
 4    ORD-3      250          2016-04-06 04:30:25 PM
 5    ORD-3      300          2016-04-06 04:30:25 PM
 6    ORD-3      750          2016-04-06 04:30:26 PM
 7    ORD-4      650          2016-04-06 08:30:26 PM
 7    ORD-4      150          2016-04-06 08:30:27 PM

Now what I want is I want to count the orders that are placed on each day, So the output should be:

count  date
  1    2016-04-04 // For ORD-1
  1    2016-04-05 // For ORD-2
  2    2016-04-06 // For ORD-3 and ORD-4

The code that I tried so far:

$ordersList = Order::latest();

$ordersListDate = $ordersList->selectRaw('date(created_at) as date')
                  ->groupBy('date')->get()
                  ->lists('date')->toArray();

$ordersListCount = $ordersList->select([
    DB::raw('DATE(created_at) AS date'),
    DB::raw('COUNT(code) AS count')
])->groupBy('date')->get()->lists('count')->toArray();

The above controller gives when I do dd($ordersListCount):

array:2 [▼
  0 => "2"
  1 => "1"
  2 => "5"
]

I am scratching my head since long time and couldn't get this done. I know there must be silly thing that I must have missed or not considering, but I am still at the learning stage.

Any help is highly appreciated. Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire