Laravel 4 - 从集合获取属性数组 [英] Laravel 4 - Get Array of Attributes from Collection
问题描述
$ 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屋!