如何在Laravel中返回数组而不是集合?

如何在Laravel中返回数组而不是集合?

问题描述:

在Laravel中,可以仅选择一个字段并将其作为集合/数组返回.

In Laravel is it possible to select only one field and return that as a set/ array.

例如,考虑链接到表foos的模型Foo,该表具有字段idabc.

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的值,其中b15,我可以这样做:

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();

Laravel的pluck()方法.

Laravel的toArray()方法.