雄辩的 ORM 幼虫5获取 ID 数组

我正在使用 Eloquent ORM laravel 5.1,我想返回一个 id 大于0的数组,我的模型称为 test

我试过了:

$test=test::select('id')->where('id' ,'>' ,0)->get()->toarray();

它返回:

Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) )

但我希望结果是这样的简单数组:

Array ( 1,2 )
223058 次浏览

read about the lists() method

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()

You could use lists() :

test::where('id' ,'>' ,0)->lists('id')->toArray();

NOTE : Better if you define your models in Studly Case format, e.g Test.


You could also use get() :

test::where('id' ,'>' ,0)->get('id');

UPDATE: (For versions >= 5.2 use 'pluck()' instead)

The lists() method was deprecated in the new versions >= 5.2, now you could use pluck() method instead :

test::where('id' ,'>' ,0)->pluck('id')->toArray();

NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:

test::where('id' ,'>' ,0)->pluck('id');

The correct answer to that is the method lists, it's very simple like this:

$test=test::select('id')->where('id' ,'>' ,0)->lists('id');

Regards!

From a Collection, another way you could do it would be:

$collection->pluck('id')->toArray()

This will return an indexed array, perfectly usable by laravel in a whereIn() query, for instance.

You can use all() method instead of toArray() method (see more: laravel documentation):

test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array

If you need a string, you can use without toArray() attachment:

test::where('id' ,'>' ,0)->pluck('id'); //returns string

Just an extra info, if you are using DB:

DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();

And if using Eloquent model:

test::where('id', '>', 0)->lists('id')->toArray();

Although you have marked the Answer, This is a much simpler approach

App\User::pluck('id')->toArray()

A simple way to get an array with the model IDs from a collection:

$test = test::select('id')->where('id' ,'>' ,0)->get('id')->modelKeys();

Available since Laravel 5.5: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Collection.html#method_modelKeys

In Laravel 8 this works for me

$arr = SomeModel::where("field", value)->get()->toArray();