仅从 Laravel 集合中获取特定属性

新手上路,请多包涵

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

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

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

在 Laravel 中似乎没有这个助手? - 我怎样才能做到这一点最简单的方法?

原文由 preyz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 471
2 个回答

您可以使用现有 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 在模型上添加了一个 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 中引入 的集合的“高阶消息传递” 结合起来,它可以进一步简化:

 // 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']);

原文由 patricus 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是对上述@patricus 答案 的跟进:

使用以下内容返回对象集合而不是数组,以便您可以使用与模型对象相同的对象,即 $subset[0]->name

 $subset = $users->map(function ($user) {
    return (object) $user->only(['id', 'name', 'email']);
});

原文由 Abdul Rehman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题