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 数组


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01