Eloquent ORM laravel 5 Get Array of ids(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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Eloquent ORM laravel 5 获取 id 数组
基础教程推荐
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- php中的PDF导出 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的foreach复选框POST 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
