如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:17:56  来源:igfitidea点击:

How to return an array instead of a collection in Laravel?

laravelmodellaravel-5

提问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 Foowhich is linked to table fooswhich has field id, a, b, c.

例如,考虑Foo链接到foos具有字段idab、 的表的模型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 awhere bis 15, I could do that like so:

现在,如果我想创建一个返回awhere bis 的所有值的查询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();

Laravel's pluck() method.

Laravel 的 pluck() 方法

Laravel's toArray() method.

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