我有一个搜索功能来搜索特定日期,月份,字符串等的费用.它返回一个集合:
到现在为止还挺好.我可以显示全部返回Expenses.现在,我想要做的是,显示总费用和总金额,按照分组description_id.如果我只是这样做$result->groupBy('description_id),我只会得到一组集合,我可以从中显示总计数和总金额,但不能显示描述的名称.我想要的例子:
Grouped Results (By Expense):
Description Name: <-- Issue displaying this
Total Expenses: 3
Total Amount: 53444
Run Code Online (Sandbox Code Playgroud)
描述名只能经由之间的关系来获得Expense和Description.费用属于描述.
在处理我的集合时,是否可以实现我想要的,或者我应该对这些结果执行单独的查询?(不期望的)
如果您急切加载description,则可以通过集合的嵌套对象对生成的集合进行分组.所以你可能有:
$expenses = Expenses::with('description')->get(); //collection
Run Code Online (Sandbox Code Playgroud)
然后分组:
$grouped = $expenses->groupBy('description.name');
//or
$grouped = $expenses->groupBy('description_id');
Run Code Online (Sandbox Code Playgroud)
然后你可以使用描述的名称,访问它,说我们需要第一组,以及组中的第一笔费用,
$description_name = $grouped
->first() //the first group
->first() //the first expense in group
->description //the description object
->name //the name
Run Code Online (Sandbox Code Playgroud)
这只是一个小证据,您可以在集合中获取相关模型的名称,并使用它来解决您的问题.