You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何获取groupBy后的分组键名列表?

提取Eloquent分组后的日期键数组

我已经通过Eloquent成功按date字段对学生数据进行groupBy分组,现在需要提取分组后的日期键名组成单独的数组,而非包含对应集合的分组结果。

我的代码

$this->StudentList = Student::get();
$data =  $this->StudentList->sortBy('date', SORT_NATURAL)->groupby('date');
 
dd($data);

当前分组结果

array:14 [▼   
  "2024-01-01" => Illuminate\Database\Eloquent\Collection {#1977 ▶}
  "2024-01-02" => Illuminate\Database\Eloquent\Collection {#1978 ▶}
  "2024-01-03" => Illuminate\Database\Eloquent\Collection {#1979 ▶}
  "2024-01-04" => Illuminate\Database\Eloquent\Collection {#1980 ▶}
  "2024-01-05" => Illuminate\Database\Eloquent\Collection {#1981 ▶}
]

期望输出

array:14 [▼   
  "2024-01-01"  
  "2024-01-02"  
  "2024-01-03"  
  "2024-01-04" 
  "2024-01-05"  
]

解决方法

方法1:利用集合的keys()方法

既然你已经拿到了分组后的集合,直接调用keys()方法就能提取所有日期键,再转成数组就符合需求了:

$this->StudentList = Student::get();
$data = $this->StudentList->sortBy('date', SORT_NATURAL)->groupby('date');
$dateArray = $data->keys()->toArray();

dd($dateArray);

方法2:直接从数据库查询去重日期(更高效)

如果你的需求只是获取所有存在的日期,完全没必要先查询所有学生数据再分组。直接用distinct()和pluck()组合,能更高效地拿到排序后的日期数组,还能减少数据传输和内存占用:

$dateArray = Student::distinct()->pluck('date')->sort()->toArray();

dd($dateArray);

内容的提问来源于stack exchange,提问作者p22222222

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:32:25