Laravel 5.2 - 更改从 Eloquent 获取的数据格式

Laravel 5.2 - Change Data Format get from Eloquent

我有这样的模型-

$feature_project = FeatureProject::select('feature_id')
                       ->where('project_id', $project->id)
                       ->get();

如果我return它,我得到这样的输出-

[
  {
    "feature_id": 2
  },
  {
    "feature_id": 4
  },
  {
    "feature_id": 9
  }
]

但是我想要这样的输出-

[2,4,9]

所以我需要转换输出。

但我找不到不使用 for-each 循环的方法(制作一个临时数组,使用 for-each 循环将所有元素从当前数组推送到该数组)。

但我认为有比 Laravel 更聪明的方法来做到这一点。

我觉得LaravelCollection就是为了这个目的

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

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

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

另一种方法在某些情况下也会有所帮助。 我们可以在select函数中运行raw查询。 这是一个例子:

$feature_project = FeatureProject::select(DB::raw('GROUP_CONCAT("feature_id")))
                   ->where('project_id', $project->id)
                   ->get();

DB::raw中我们可以运行 mysql查询,功能和大小写与mysql查询相同。

在Laravel的集合中,您可以调用一个名为 Flatten 的方法,它将多维集合扁平化为一个维度。

https://laravel.com/docs/5.2/collections#method-flatten

$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);

$flattened = $collection->flatten();

$flattened->all();

// ['taylor', 'php', 'javascript'];

对于一个相当扁平的对象,它应该 return 只是值。

使用pluck():

$feature_project = FeatureProject::where('project_id', $project->id)->pluck('feature_id');

您可以使用 lists()toArray() :

$feature_project=FeatureProject::where('project_id', $project->id)->lists('id')->toArray();

希望对您有所帮助。