过滤现有模型数据 laravel
Posted
技术标签:
【中文标题】过滤现有模型数据 laravel【英文标题】:Filter existing model data laravel 【发布时间】:2019-02-18 06:25:12 【问题描述】:我有一个使用 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
];
【问题讨论】:
“无法使第二个 foreach 循环工作”是什么意思?预期结果与实际结果如何? @JonasStaudenmeir 第二个 for 循环产生错误,我最终不得不做另一个原始 DB::select 调用,理想情况下我想避免这种情况,因为所有信息都在创建的模型中跨度> 错误是什么? @JonasStaudenmeir 问题出在数据格式上。我会用更多代码更新问题。 预期结果与实际结果是什么? 【参考方案1】:您的 laravel 查询生成器不正确,请尝试:$EntryClass = $ReportData->where('Office', '=', $OfficeName)->groupBy('Manager')->get();
您最后错过了get()
,这导致 laravel 不将数据收集到数组中,groupBy
也按照 documentation 进行了驼峰化处理
【讨论】:
以上是关于过滤现有模型数据 laravel的主要内容,如果未能解决你的问题,请参考以下文章