您可以使用现有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 中的每个项目传递给传入的回调。每次调用回调返回的值构建由map() 方法生成的新Collection。
collect($user->toArray()) 只是从Users 属性中构建一个新的临时Collection。
->only(['id', 'name', 'email']) 将临时 Collection 减少到仅指定的那些属性。
->all() 将临时的Collection 转换回普通数组。
把它们放在一起,你会得到“对于 users 集合中的每个用户,返回一个仅包含 id、name 和 email 属性的数组。”
Laravel 5.5 更新
Laravel 5.5 在 Model 上添加了一个only 方法,其作用与collect($user->toArray())->only([...])->all() 基本相同,因此在 5.5+ 中可以稍微简化为:
// 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 中引入的 "higher order messaging" for collections 结合起来,它可以进一步简化:
// 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']);