如何将收集结果作为带有 id 的数组获取

how to get collection results as array with ids

应该很简单,但我遗漏了一些东西, 让我们说这个简单的 eloquent:

Post::select('id')->take(5)->get();

我想获得带有结果 ID 的简单数组,因此它看起来像这样:

[1,2,3,4,5]

但我得到这样的结果:

[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}]

flatten() 不工作,我得到相同的结果:

Post::select('id')->take(5)->get()->flatten();

http://laravel.com/docs/master/collections#method-flatten

The flatten method flattens a multi-dimensional collection into a single dimension:

我错过了什么?我记得有一条短线 laravel 方法可以在不遍历数组并创建新数组的情况下获得此结果

刚知道,它的 lists() 很神奇,所以答案是:

Post::select('id')->take(5)->lists('id');

更新: 从 laravel 5.2 开始,lists() 变为 deprecated

The lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same.

新方法名为 pluck,作用相同:

Post::select('id')->take(5)->pluck('id');