我一直在审查Laravel的文档和API,但似乎找不到我要找的东西:
我想从集合中检索带有模型数据的数组,但只获取指定的属性。
例如,类似于Users::toArray('id','name','email')
,集合实际上为用户保存所有属性,因为它们在其他地方使用,但是在这个特定的地方,我需要一个带有userdata的数组,并且只需要指定的属性。
在拉拉维尔似乎没有一个帮手?-我怎么才能做到这一点呢?
发布于 2016-07-18 05:18:51
您可以使用现有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())
只是从Users
属性构建一个新的临时Collection
。
->only(['id', 'name', 'email'])
将临时Collection
降至仅指定的那些属性。
->all()
将临时Collection
转换回普通数组。
把它们放在一起,您就可以得到“用户集合中的每个用户,返回一个只包含id、name和email属性的数组”。
Laravel 5.5更新
Laravel5.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']);
});
如果将此与Laravel5.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']);
发布于 2016-07-16 15:46:27
使用User::get(['id', 'name', 'email'])
,它将返回一个包含指定列的集合,如果要使其成为数组,只需在get()
方法之后使用toArray()
,如下所示:
User::get(['id', 'name', 'email'])->toArray()
大多数情况下,您不需要将集合转换为数组,因为集合实际上是类固醇上的数组,而且您有易于使用的方法来操作集合。
发布于 2020-02-11 13:54:21
下面的方法也有效。
$users = User::all()->map(function ($user) {
return collect($user)->only(['id', 'name', 'email']);
});
https://stackoverflow.com/questions/38412091
复制相似问题