雄辩的ORM laravel 5获取ID数组 [英] Eloquent ORM laravel 5 Get Array of ids
问题描述
我正在使用Eloquent ORM laravel 5.1,我想返回一个ID大于0的数组,我的模型称为test
.
I'm using Eloquent ORM laravel 5.1, i want to return an array of ids greater than 0, My model called test
.
我尝试过:
$test=test::select('id')->where('id' ,'>' ,0)->get()->toarray();
返回:
Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) )
但是我希望结果以简单的数组形式出现:
But i want result to be in simple array like :
Array ( 1,2 )
推荐答案
您可以使用 lists()
:
You could use lists()
:
test::where('id' ,'>' ,0)->lists('id')->toArray();
注意:如果您以Studly Case
格式(例如Test
)定义模型,效果更好.
NOTE : Better if you define your models in Studly Case
format, e.g Test
.
您还可以使用 get()
:
test::where('id' ,'>' ,0)->get('id');
更新: (对于版本== 5.2)
在新版本>= 5.2
中, lists()
方法已被 弃用,现在您可以使用 pluck()
方法:
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();
注意: 如果需要字符串,例如在刀片中,则可以使用不带 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');
这篇关于雄辩的ORM laravel 5获取ID数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!