简体   繁体   English

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

[英]Laravel preserve group keys in collection serialization

Laravel v.5.8: Laravel v.5.8:

I want to group each child relation budgets and json serialize it.我想对每个子关系预算进行分组,并 json 对其进行序列化。

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

which will return:这将返回:

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

but using dd($monthbudgets[8]->jsonSerialize()) , it will return:但使用dd($monthbudgets[8]->jsonSerialize()) ,它将返回:

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

Looks like it flattens it and removes the keys (1, 5).看起来它会将其压平并移除键(1、5)。

I'm also open to suggestions for minimizing the grouping loop.我也对最小化分组循环的建议持开放态度。 I tried我试过了

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

which will result in这将导致

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

Laravel's jsonSerialize will call toArray : Laravel 的jsonSerialize将调用toArray

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

which merges the attributes and then the relations which makes it overwrite the attribute you've set.它合并属性,然后合并关系,使其覆盖您设置的属性。

You can set the relation with setRelation您可以使用setRelation设置关系

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM