Eloquent ORM laravel 5 获取 id 数组 [英] Eloquent ORM laravel 5 Get Array of ids

查看:42
本文介绍了Eloquent ORM laravel 5 获取 id 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆