Laravel在集合序列化中保留组密钥



Laravel v.5.8:

我想对预算的每个子关系进行分组,并对其进行json序列化。

$monthbudgets = AppBudgetMonth::where('month', $curmonth)->with("budgets")->get();
foreach ($monthbudgets as $month) {
$month->budgets = $month->budgets->groupBy("customer_id");
}
dd($monthbudgets[8]);

将返回:

//laravel collection of "budgets"
...[
1 => [
0 => []
1 => []
],
5 => [
0 => []
]
]...

但是使用dd($monthbudgets[8]->jsonSerialize()),它将返回:

//array of "budgets"
...[
0 => []
1 => []
2 => []
]...

看起来它会使其变平并删除关键点(1,5(。

我也对最小化分组循环的建议持开放态度。我试过

->with(["budgets" => function ($query) {
$query->groupBy("customer_id");
}])->get();

这将导致

Syntax error or access violation: 1055 'budgets.id' isn't in GROUP BY (...)

Laravel的jsonSerialize将调用toArray:

// Model.php
public function toArray()
{
return array_merge($this->attributesToArray(), $this->relationsToArray());
}

它合并属性,然后合并使其覆盖您设置的属性的关系。

可以使用setRelation设置关系

foreach ($monthbudgets as $month) {
$month->setRelation('budgets', $month->budgets->groupBy("customer_id"));
}

最新更新