仅从 Laravel Collection 中获取特定属性

2022-08-30 07:20:06

我一直在审查Laravel Collections的文档和API,但似乎没有找到我想要的东西:

我想从集合中检索包含模型数据的数组,但只获取指定的属性。

即类似的东西,其中集合实际上保存了用户的所有属性,因为它们在其他地方使用,但是在这个特定的地方,我需要一个包含userdata的数组,并且只有指定的属性。Users::toArray('id','name','email')

在拉拉维尔似乎没有这方面的帮手?- 我怎样才能以最简单的方式做到这一点?


答案 1

您可以使用现有方法的组合来执行此操作。起初可能有点难以理解,但它应该很容易分解。Collection

// get your main collection with all the attributes...
$users = Users::get();

// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
    return collect($user->toArray())
        ->only(['id', 'name', 'email'])
        ->all();
});

解释

首先,该方法基本上只是循环访问 ,并将 中的每个项传递给传入的回调。从每次调用回调返回的值将生成由该方法生成的新值。map()CollectionCollectionCollectionmap()

collect($user->toArray())只是构建一个新的,暂时出来的属性。CollectionUsers

->only(['id', 'name', 'email'])将临时值减少到仅指定那些属性。Collection

->all()将临时数组转换回普通数组。Collection

将它们放在一起,您将获得“对于user集合中的每个用户,仅返回一个仅包含id,名称和电子邮件属性的数组。


拉拉维尔 5.5 更新

Laravel 5.5 在模型上添加了一个方法,该方法基本上与 相同,因此可以在 5.5+ 中稍微简化为:onlycollect($user->toArray())->only([...])->all()

// get your main collection with all the attributes...
$users = Users::get();

// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
    return $user->only(['id', 'name', 'email']);
});

如果您将其与Laravel 5.4中引入的集合的“高阶消息传递”相结合,则可以进一步简化:

// get your main collection with all the attributes...
$users = Users::get();

// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map->only(['id', 'name', 'email']);

答案 2

use ,它将返回一个包含指定列的集合,如果您想使其成为数组,只需在方法之后使用,如下所示:User::get(['id', 'name', 'email'])toArray()get()

User::get(['id', 'name', 'email'])->toArray()

大多数情况下,您不需要将集合转换为数组,因为集合实际上是类固醇上的数组,并且您有易于使用的方法来操作集合。


推荐