Eloquent ORM laravel 5 获取 id 数组

2021-12-26 00:00:00 model php laravel laravel-5 eloquent

我使用的是 Eloquent ORM laravel 5.1,我想返回一个大于 0 的 id 数组,我的模型叫做 test.

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

我试过了:

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

它返回:

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

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

But I want the result to be in simple array like this:

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)

lists() 方法在新版本 >= 5.2不推荐使用,现在你可以使用 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();

注意:如果您需要 string,例如在 blade 中,您可以使用没有 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');

相关文章