我一直在查看Laravel系列的文档和API,但似乎没有找到我想要的:
我想从集合中检索包含模型数据的数组,但只获取指定的属性.
例如,大约Users::toArray('id','name','email')
,其中集合实际上保存用户的所有属性,因为它们在其他地方使用,但在这个特定位置,我需要一个包含userdata的数组,并且只包含指定的属性.
在拉雷维尔似乎没有帮手我怎样才能用最简单的方法做到这一点?
我一直在查看Laravel系列的文档和API,但似乎没有找到我想要的:
我想从集合中检索包含模型数据的数组,但只获取指定的属性.
例如,大约Users::toArray('id','name','email')
,其中集合实际上保存用户的所有属性,因为它们在其他地方使用,但在这个特定位置,我需要一个包含userdata的数组,并且只包含指定的属性.
在拉雷维尔似乎没有帮手我怎样才能用最简单的方法做到这一点?
您可以使用现有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();
});
Explanation
首先,map()
方法基本上只是迭代Collection
,并将Collection
中的每一项传递给传入的回调.从每次回调调用返回的值构建由map()
方法生成的新Collection
.
collect($user->toArray())
只是在Users
个属性中建立一个新的、临时的Collection
个.
->only(['id', 'name', 'email'])
将临时Collection
降低到仅指定的那些属性.
->all()
将临时Collection
变回普通array.
把它们放在一起,你会得到"对于用户集合中的每个用户,只返回id、名称和邮箱属性的array."
Laravel 5.5在模型上添加了一个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']);