更改已加载的数组键

Jam*_*mie 0 php arrays eager-loading laravel

我有几个eager loaded关系Laravel 5.6.我想将数组键名更改为eager加载对象上的属性.

所以,让我说我已经急切地加载了这个: 在此输入图像描述

如何确保数组键01成为name属性(" COSTS"和" SAIL_BOAT_FRIENDLY")?

这甚至可能吗?

- 编辑

return Port::filter($filters)
            ->with('scores')
            ->actives()
            ->paginate(14);
Run Code Online (Sandbox Code Playgroud)

得分关系

public function scores()
{
    return $this->hasMany(Score::class)
        ->select("id", "port_id", "name", DB::raw('AVG(score) as score'))
        ->groupBy('port_id', 'name');
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eir 5

你可以使用keyBy():

$ports = Port::filter($filters)
        ->with('scores')
        ->actives()
        ->paginate(14);

foreach($ports as $port) {
    $port->setRelation('scores', $port->scores->keyBy('name'));
}
Run Code Online (Sandbox Code Playgroud)