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

Laravel数据分组查询及stdClass转数组报错求助

Laravel查询分组问题求助

我需要对数据库esiti_audit表中的master_zone、subarea、microarea三列进行分组去重,同时展示每个分组对应的所有审计日期data_audit和审计结果esito——比如同一分组出现3次时,只显示一次分组信息,把该分组的所有审计日期和对应结果分别列出来,最终用来生成图表。

我写了下面的代码,但没得到预期结果,还抛出了「Cannot use object of type stdClass as array」错误,求帮忙找出问题并解决。

我的代码

$area = DB::table('esiti_audit')->select([
    'master_zone', 'subarea', 'microarea',
    'data_audit', 'esito'
  ])
  ->where('employee', $name)
  ->orderByDesc('data_audit')
  ->get()->toArray();

$data = [];

foreach($area as $audit) {
  
  $areaKey = "{$audit['master_zone']}|{$audit['subarea']}|{$audit['microarea']}";

  $data[$areaKey][] = [
    'esito' => $audit['esito'],
    'data_audit' => $audit['data_audit']
  ];
}

问题截图

问题截图1
问题截图2

问题原因与修正方案

错误原因

Laravel中DB::table()->get()返回的是包含stdClass对象的集合,即使调用toArray(),只是把集合转成数组,里面的每个元素依然是stdClass对象,不能用数组下标$audit['xxx']的方式访问属性,必须用对象属性访问符$audit->xxx。

修正后的代码

$area = DB::table('esiti_audit')->select([
    'master_zone', 'subarea', 'microarea',
    'data_audit', 'esito'
  ])
  ->where('employee', $name)
  ->orderByDesc('data_audit')
  ->get(); // 不需要转toArray(),直接用集合操作更方便

$data = [];

foreach($area as $audit) {
  // 用对象属性访问方式获取字段值
  $areaKey = "{$audit->master_zone}|{$audit->subarea}|{$audit->microarea}";

  $data[$areaKey][] = [
    'esito' => $audit->esito,
    'data_audit' => $audit->data_audit
  ];
}

更简洁的Laravel集合写法

可以直接用Laravel集合的groupBy方法,无需手动循环:

$groupedData = DB::table('esiti_audit')
    ->select(['master_zone', 'subarea', 'microarea', 'data_audit', 'esito'])
    ->where('employee', $name)
    ->orderByDesc('data_audit')
    ->get()
    ->groupBy(function ($item) {
        return "{$item->master_zone}|{$item->subarea}|{$item->microarea}";
    });

// 如果需要转成数组格式,可调用toArray()
$data = $groupedData->toArray();

这样处理后,$data里的每个键就是唯一的分组标识,对应的值就是该分组下所有的审计日期和结果数组,符合生成图表的数据结构需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 07:06:16