繁体   English   中英

Eloquent ORM laravel 5 获取 id 数组

[英]Eloquent ORM laravel 5 Get Array of ids

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 ) )

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

Array ( 1,2 )

您可以使用lists()

test::where('id' ,'>' ,0)->lists('id')->toArray();

注意:如果您以Studly Case格式定义模型会更好,例如Test


您也可以使用get()

test::where('id' ,'>' ,0)->get('id');

更新:(对于 >= 5.2 的版本,请改用“pluck()”)

在新版本>= 5.2不推荐使用lists()方法,现在您可以使用pluck()方法:

test::where('id' ,'>' ,0)->pluck('id')->toArray();

注意:如果您需要一个字符串,例如在刀片中,您可以使用 function 而不使用toArray()部分,例如:

test::where('id' ,'>' ,0)->pluck('id');

Collection ,您可以这样做的另一种方法是:

$collection->pluck('id')->toArray()

这将返回一个索引数组,laravel 在whereIn()查询中完全可以使用它。

正确的答案是方法lists ,它非常简单,如下所示:

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

问候

您可以使用all()方法而不是toArray()方法(查看更多: laravel 文档):

test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array

如果你需要一个string ,你可以使用没有toArray()附件:

test::where('id' ,'>' ,0)->pluck('id'); //returns string

只是一个额外的信息,如果你使用DB

DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();

如果使用 Eloquent model:

test::where('id', '>', 0)->lists('id')->toArray();

阅读有关 lists() 方法的信息

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()

从集合中获取具有 model ID 的数组的简单方法:

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

自 Laravel 5.5 起可用: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Collection.html#method_modelKeys

尽管您已标记答案,但这是一种更简单的方法

App\User::pluck('id')->toArray()

在 Laravel 8 这对我有用

$arr = SomeModel::where("field", value)->get()->toArray();

您还可以使用 all() 方法来获取选定属性的数组。

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

问候

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM