-->

How to return an array instead of a collection in

2020-08-09 05:08发布

问题:

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

For example consider the model Foo which is linked to table foos which has field 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:

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]

回答1:

Just use pluck() and ->toArray():

Foo::where('b', 15)->pluck('a')->toArray();

Laravel's pluck() method.

Laravel's toArray() method.



回答2:

Do

Foo::where('b', 15)->lists('a')->all();

This will give you an array of ids. eg [2, 3, 5]



回答3:

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.

Foo::select('a')->where('b', 15)->get()->all();