我一直在查看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更新

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

Php相关问答推荐

在WooCommerce中处理客户总支出中的退款

wp_enqueue_scripts not loading(基于类的插件)

如何将对我的域的请求重定向到子文件夹中的索引,同时保留域URL并使用.htaccess?

Htaccess-重写对&api.php";的API请求以及对";web.php";的其他请求

在Laravel Eloquent中实现一对多关系

为什么在我的PHP联系人脚本中开机自检后出现未定义变量错误?

使用PHP编码的字符串与使用OpenSSL编写的shell 代码之间的差异

将WooCommerce WC_Order对象与wp_Schedule_Event一起使用

fpm-php + nginx + POST数据

ANTLR4-lexer如何消耗更多的 token 并停止现有规则?

Mockery在模拟Redis连接时抛出错误:Mockery\Exception\BadMethodCallException

Shopware 6 插件:如何删除/迁移布尔配置到多选配置

如何为自定义帖子类型的自定义角色提供功能

使用 Laravel 和 Vue 进行图像表单验证

我的功能以舒适的方式显示数组 struct

仅允许减少 WooCommerce 中已完成订单的库存数量

在 GA4 Data API V1 Beta 中使用 inListFilter 过滤器时出错

如何为多个表的id列设置不同的值

mysql / sql修复多对多数据库中的行

PHP - 如何获取发送到脚本的查询参数