[英]How do I get GroupBy count from an eloquent collection?
我一直在四處尋找實現這一目標的方法,但是找不到解決方案。
我必須獲取會話詳細信息和計數。 我正在使用以下代碼,但在按日期對集合進行分組之后,就如何獲得計數了問題。
這是代碼:
$sessions = Session::where('api_token','1')
->orderBy('created_at', 'DESC')
->get(array(DB::raw('date(created_at) as v_date')));
//To get the total session counts -
$total_sessions = $sessions->count();
//To get the sessions that happened today -
$today_sessions = $sessions->filter(function($today)
{ if ($today->v_date == date("Y-m-d")) { return true; }})->count();
現在,我使用groupBy()將集合分組
$sessions->groupBy('v_date'));
但是,如何從該集合中檢索會話計數和日期。
預期產量:
2014-02-01 10
2014-02-02 11
2014-02-04 15
2014-02-06 70
2014-02-07 90
2014-02-08 100
如果您只是想獲取每天的會話數,則無需使用Eloquent,您可以使用查詢生成器。
$sessions = DB::table('sessions')
->select(DB::raw('date(created_at) AS v_date, count(*) AS count'))
->where('api_token', '1')
->orderBy('v_date', 'desc')
->groupBy('v_date')
->get();
這將返回代表每一行的對象數組:
array (size=1)
0 =>
object(stdClass)[346]
public 'v_date' => string '2014-03-09' (length=10)
public 'count' => int 2
1 =>
object(stdClass)[349]
public 'v_date' => string '2014-03-08' (length=10)
public 'count' => int 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.