Laravel 5.2 - 更改数据格式来自Eloquent

Abr*_*hin 6 php laravel laravel-5 laravel-5.1 laravel-5.2

我有这样的模特 -

$feature_project = FeatureProject::select('feature_id')
                       ->where('project_id', $project->id)
                       ->get();
Run Code Online (Sandbox Code Playgroud)

如果我退回,我会得到这样的输出 -

[
  {
    "feature_id": 2
  },
  {
    "feature_id": 4
  },
  {
    "feature_id": 9
  }
]
Run Code Online (Sandbox Code Playgroud)

但我想要像这样输出 -

[2,4,9]
Run Code Online (Sandbox Code Playgroud)

所以我需要转换输出.

但我没有使用for-each循环找到一种方法(做一个临时数组,推到该数组的所有元素从当前阵列与for-each循环).

但我认为在Laravel中有更聪明的方法来做到这一点.

我认为Laravel Collection用于此目的.

Kas*_*ars 4

您可以调用pluck()查询生成器上的方法。

$feature_project = FeatureProject::select('feature_id')
                                        ->where('project_id', $project->id)
                                        ->pluck('feature_id'); // [2,4,9]
Run Code Online (Sandbox Code Playgroud)

https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_lists

或者,您可以使用 PHP 的array_column()原始数组函数。 http://php.net/manual/en/function.array-column.php