如何在 Laravel 中返回数组而不是集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35857297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return an array instead of a collection in Laravel?
提问by Yahya Uddin
In Laravel is it possible to select only one field and return that as a set/ array.
在 Laravel 中是否可以只选择一个字段并将其作为集合/数组返回。
For example consider the model Foo
which is linked to table foos
which has field id
, a
, b
, c
.
例如,考虑Foo
链接到foos
具有字段id
、a
、b
、 的表的模型c
。
Consider the following sample data:
考虑以下示例数据:
(1, 10, 15, 20)
(1, 12, 15, 27)
(1, 17, 15, 27)
(1, 25, 16, 29)
(1, 28, 16, 40)
Now if I wanted to create a query that returns all the values of a
where b
is 15
, I could do that like so:
现在,如果我想创建一个返回a
where b
is 的所有值的查询15
,我可以这样做:
Foo::select('a')->where('b', 15)->get();
However this will return an eloquent collection.
然而,这将返回一个雄辩的集合。
Instead how can I return instead an array like this:
相反,我如何才能返回这样的数组:
[10, 12, 17]
回答by Mushr00m
Just use pluck()
and ->toArray()
:
只需使用pluck()
和->toArray()
:
Foo::where('b', 15)->pluck('a')->toArray();
回答by oseintow
Do
做
Foo::where('b', 15)->lists('a')->all();
This will give you an array of ids. eg [2, 3, 5]
这将为您提供一组 id。例如 [2, 3, 5]
回答by Moeen Basra
The lists method is deprecated and pluck need some parameter so, if you want to get all the attributed in array format, use it this way.
不推荐使用列表方法,并且 pluck 需要一些参数,因此,如果您想以数组格式获取所有属性,请以这种方式使用。
Foo::select('a')->where('b', 15)->get()->all();
Foo::select('a')->where('b', 15)->get()->all();