【问题标题】:How do I get GroupBy count from an eloquent collection?如何从 eloquent 集合中获取 GroupBy 计数?
【发布时间】:2014-04-03 06:44:53
【问题描述】:

我一直在寻找很多东西来实现这一点,但还没有找到解决方案。

我必须获取会话详细信息和计数。我正在使用以下代码,但坚持在按日期对集合进行分组后如何获取计数。

代码如下:

$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

【问题讨论】:

  • 我被你的问题弄糊涂了,真的没明白,你的意思是$sessions->groupBy('v_date'))->count();
  • 你能改写你的问题吗?
  • @WereWolf-TheAlpha - 我有表会话。我在我的集​​合 $sessions 中检索 api_token 的所有数据。现在我需要三个值。 1- 总会话数。 2- 今天发生的会话计数。 3-日期明智的会话计数。现在就像问题一样,我可以得到 1 和 2。如何从集合中获取按日期计算的计数?

标签: php collections laravel


【解决方案1】:

如果您只是想计算每天的会话数,则无需使用 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

【讨论】:

  • 谢谢@RMcLeod 我想从收藏中得到三件事。 1- 总会话数。 2- 今天发生的会话计数。 3- 日期明智的会话计数。
猜你喜欢
  • 2021-04-10
  • 2016-06-23
  • 2021-09-08
  • 2020-05-22
  • 1970-01-01
  • 2021-04-24
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多