3

I have a model populated using hydrate, I now need to loop through this model and against each office return a new instance of the model. However, I cannot get the second foreach loop to work no matter what I try.

Sadly the $data array needs to be in this format, and I can't query the table multiple times as it is a temporary table and may disappear.

$Model = new RegionModel();
$ReportReturnData = App::make('stdClass');
$Query = "SELECT Region, Office, Manager, SUM(Bills) AS Bills FROM ##TMP_ReportData GROUP BY Region, Office, Manager";
$ReportData = $Model->hydrate(
    DB::select($query)
);
$Offices = $ReportData->unique('Office')->pluck('Office');
foreach ($Offices as $Office)//This loop works fine
{
    $Class = App::make('stdClass');
    $OfficeName = $Office;
    $Entries = [];
    $TotalBilled = 0;
    $EntryClass = $ReportData->where('Office', '=', $OfficeName)->groupby('Manager');// this doesn't work.

    // at present I have to do this which adds extra load on the DB
    $SubQuery = "SELECT Manager, SUM(Bills) AS Bulls FROM ##TMP_ReportData WHERE Office = ? GROUP BY Manager";
    $EntryClass = DB::select($SubQuery , [$OfficeName]);

    foreach ($EntryClass as $Entry){
        $Line = App::make('stdClass');
        $Line->Office=$OfficeName;
        $Line->Manager = $Entry->Manager;
        $Line->Bills = $Entry->Bills;
        $TotalBilled += $Entry->Bills;
        $Entries[] = $Line;
    }
    $Class->Name = $OfficeName;
    $Class->TotalBilled = $TotalBilled;
    $Class->Entries = $Entries;
    $ReportReturnData->Offices[] = $Class;
}
$Total = App::make('stdClass');
$Total->TotalBilled = $ReportData->sum('Bills');
$data = [
        'RegionName' => $RegionName,
        'DateFrom' => $DateFrom,
        'DateTill' => $DateTill,

        'Entries' => $ReportReturnData,
        'AVG' => $AVG,
        'Total' => $Total,

        'ReportDate' => $ReportDate,
        'LogoImage' => $LogoImage
    ];
Neo
  • 2,305
  • 4
  • 36
  • 70

1 Answers1

0

Your laravel query builder is incorrect, try with: $EntryClass = $ReportData->where('Office', '=', $OfficeName)->groupBy('Manager')->get();

You missed the get() at the end which caused laravel to don't collect the data into an array, also groupBy is camelcased as per the documentation

Sven Hakvoort
  • 3,543
  • 2
  • 17
  • 34