Eloquent ORM laravel 5 Get Array of ids

2019-02-01 04:34发布

I'm using Eloquent ORM laravel 5.1, i want to return an array of ids greater than 0, My model called test.

I have tried :

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

It return :

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

But i want result to be in simple array like :

Array ( 1,2 )

5条回答
劫难
2楼-- · 2019-02-01 04:40

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.

查看更多
疯言疯语
3楼-- · 2019-02-01 04:40

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!

查看更多
再贱就再见
4楼-- · 2019-02-01 04:42

read about the lists() method

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
查看更多
放我归山
5楼-- · 2019-02-01 04:55

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)

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();
查看更多
该账号已被封号
6楼-- · 2019-02-01 04:57

You may also use all() method to get array of selected attributes.

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

Regards

查看更多
登录 后发表回答