如何在Laravel中返回数组而不是集合?
问题描述:
在Laravel中,可以仅选择一个字段并将其作为集合/数组返回.
In Laravel is it possible to select only one field and return that as a set/ array.
例如,考虑链接到表foos
的模型Foo
,该表具有字段id
,a
,b
,c
.
For example consider the model Foo
which is linked to table foos
which has field id
, a
, b
, c
.
请考虑以下示例数据:
(1, 10, 15, 20)
(1, 12, 15, 27)
(1, 17, 15, 27)
(1, 25, 16, 29)
(1, 28, 16, 40)
现在,如果我想创建一个查询,该查询返回所有a
的值,其中b
是15
,我可以这样做:
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:
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]
答
只需使用pluck()
和->toArray()
:
Foo::where('b', 15)->pluck('a')->toArray();