gpt4 book ai didi

eloquent - 过滤现有模型数据 laravel

转载 作者:行者123 更新时间:2023-12-01 08:13:53 24 4
gpt4 key购买 nike

我有一个使用 hydrate 填充的模型,我现在需要遍历这个模型并针对每个办公室返回一个新的模型实例。但是,无论我尝试什么,我都无法让第二个 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
];

最佳答案

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

你错过了最后的 get() 导致 laravel 没有将数据收集到数组中,而且 groupBy 是按照 documentation 驼峰式命名的

关于eloquent - 过滤现有模型数据 laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52315040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com