您可以使用现有方法的组合来执行此操作。起初可能有点难以理解,但它应该很容易分解。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()
Collection
Collection
Collection
map()
collect($user->toArray())
只是构建一个新的,暂时出来的属性。Collection
Users
->only(['id', 'name', 'email'])
将临时值减少到仅指定那些属性。Collection
->all()
将临时数组转换回普通数组。Collection
将它们放在一起,您将获得“对于user集合中的每个用户,仅返回一个仅包含id,名称和电子邮件属性的数组。
拉拉维尔 5.5 更新
Laravel 5.5 在模型上添加了一个方法,该方法基本上与 相同,因此可以在 5.5+ 中稍微简化为:only
collect($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']);