过滤现有模型数据

时间:2018-09-13 13:41:28

标签: eloquent laravel-5.4 php-7.2

我有一个使用水合物填充的模型,现在我需要遍历此模型,并针对每个办公室返回该模型的新实例。但是,无论尝试什么,我都无法使第二个foreach循环正常工作。

不幸的是,$ data数组必须采用这种格式,并且我不能多次查询该表,因为它是一个临时表,并且可能会消失。

$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
    ];

1 个答案:

答案 0 :(得分:0)

您的laravel查询生成器不正确,请尝试:$EntryClass = $ReportData->where('Office', '=', $OfficeName)->groupBy('Manager')->get();

您错过了最后的get(),这导致laravel不能将数据收集到数组中,groupBy也按照documentation进行了驼峰式