問題描述
我使用的是 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');
這篇關于Eloquent ORM laravel 5 獲取 id 數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!