select certain columns from eloquent collection after the query has executed

Typ*_*101 1 collections laravel

Using Laravel 5.3, I have a model with the following function

public function myData() {
    return $this->hasMany(MyData::class);
}
Run Code Online (Sandbox Code Playgroud)

and in my collection I have the following

$my_data = MyModel->myData()->get(); 
Run Code Online (Sandbox Code Playgroud)

All good so far. If I return $my_data I get an eloquent collection with three items.

What I need now though is to create a duplicate of that collection but containing only three of the fields.

I have tried several different things, each of which return an error. The following is the closest I have got, but this returns an empty array - I assume because the fields are located one level deeper than the collection object.

$new_collection = $my_data->only(['field_1', 'field_2', 'field_3']);
Run Code Online (Sandbox Code Playgroud)

What would be the correct way to create a new collection containing all three items, each with only the three selected fields?

Thanks for your help

Dou*_*aan 5

您可以使用map

$slimmed_down = $collection->map(function ($item, $key) {
    return [
        'field_1' => $item->field_1,
        'field_2' => $item->field_2,
        'field_3' => $item->field_3
    ];
});
Run Code Online (Sandbox Code Playgroud)

这将返回Collection仅包含所需值的新值。据我所知,没有任何其他方法可以满足您的需求,因此对每个项目进行迭代并以这种方式选择字段是少数解决方案之一。

使用map而不是标准foreach循环的好处是,当您使用map它时,它会返回的新实例Collection

编辑:

经过一番思考和研究之后,您将创建的问题是,这些值Collection不再是任何实例。如果您不介意这种效果,那么更漂亮,更快捷的方法是:

$slimmed_down = $collection->toArray()->only(['field_1', 'field_2', 'field_3']);
Run Code Online (Sandbox Code Playgroud)

这基本上具有相同的结果。

  • 您不能对“toArray()”的结果调用“only”。因为它是一个数组,而不是一个集合。 (6认同)

小智 5

使用 Laravel 9,我遇到了同样的问题:

$my_data->only(['field_1', 'field_2', 'field_3']);

返回一个空数组。我用以下方法解决了它:

$my_data->map->only(['field_1', 'field_2', 'field_3']);
Run Code Online (Sandbox Code Playgroud)