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

如何访问Laravel Eloquent Model数组属性中的reportItems

解决方法

你添加的reportItems和reportItemsSum属于模型的动态属性,可以通过两种方式直接访问:

  • 直接通过模型实例访问(Laravel模型支持魔术属性,即使属性存在attributes数组里也能直接调用):

    // 遍历分组后的报告数据
    foreach ($reportsGrouped as $date => $reports) {
        foreach ($reports as $report) {
            // 获取reportItems集合
            $items = $report->reportItems;
            // 获取计算的总和
            $sum = $report->reportItemsSum;
            
            // 遍历reportItems里的具体数据
            foreach ($items as $item) {
                // 示例:输出单个商品的总和
                echo $item->report_product_sum;
            }
        }
    }
    
  • 如果模型被转为数组/JSON格式,就通过数组键名访问:

    $reportArray = $report->toArray();
    $items = $reportArray['reportItems'];
    $sum = $reportArray['reportItemsSum'];
    

额外代码优化建议

你当前的代码存在重复查询的问题,可以通过定义模型关联来简化逻辑:

  1. 给Report模型添加关联方法:
    class Report extends Model
    {
        public function reportItems()
        {
            return $this->hasMany(ReportItem::class, 'report_id');
        }
    }
    
  2. 简化原代码,避免重复编写where条件:
    $reportsGrouped = $pharmacy->pharmacyReportIndetificator->reportItem
        ->pluck('report')
        ->unique('report_id')
        ->map(function($report) use($pharmacy) {
            $pibCode = $pharmacy->pharmacyReportIndetificator->pharmacy_pib;
            // 直接通过关联筛选数据
            $reportItems = $report->reportItems()->where('report_pharmacy_pib_code', $pibCode)->get();
            
            $report->reportItemsSum = $reportItems->sum('report_product_sum');
            $report->reportItems = $reportItems;
            return $report;
        })
        ->sortBy('report_date')
        ->groupBy('report_date');
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:39:17