Laravel 4 - 从集合获取属性数组 [英] Laravel 4 - Get Array of Attributes from Collection

查看:183
本文介绍了Laravel 4 - 从集合获取属性数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象的集合。假设对象是标签:

  $ tags = Tag :: all(); 

我想为每个标签检索一个特定的属性,比如说它的名字。当然我可以做

  foreach($ tags as $ tag){
$ tag_names [] = $ tag- >名称;
}

但是,这个问题有更多的方便的解决方案吗?



$ tags-> name

解决方案

集合有一个列表方法,类似于@Gadoma描述的表的方法。它返回一个数组,其中包含集合中每个项目的给定属性的值。



要从我的标签集中检索所需的名称数组,我可以简单地使用:

  $ tags-> lists('name'); 

更新:截至 laravel 5.2 code>列表替换为 pluck

  $ tags-> pluck('name'); 

更具体地说, laravel 5.2升级指南指出集合,查询构建器和Eloquent查询构建器对象中的列表方法已被重命名为 pluck 。方法签名保持不变。


I have a collection of objects. Let's say the objects are tags:

$tags = Tag::all();

I want to retrieve a certain attribute for each tag, say its name. Of course I can do

foreach ($tags as $tag) {
    $tag_names[] = $tag->name;
}

But is there a more laravelish solution to this problem?

Something like $tags->name?

解决方案

Collections have a lists method similar to the method for tables described by @Gadoma. It returns an array containing the value of a given attribute for each item in the collection.

To retrieve the desired array of names from my collection of tags I can simply use:

$tags->lists('name');

Update: As of laravel 5.2 lists is replaced by pluck.

$tags->pluck('name');

More specifically, the laravel 5.2 upgrade guide states that "[t]he lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same."

这篇关于Laravel 4 - 从集合获取属性数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆