使用Eloquent在一个数组中获取列的所有值

时间:2016-03-10 12:28:28

标签: arrays select eloquent

我想在单个数组中获取特定列的所有值。寻找可以做到这一点的雄辩功能。

这样的事情:

Model::select('id')->where('type', 'user')->asArray()

预期结果是:

[1,2,3,4,5,6,7,8,9]

1 个答案:

答案 0 :(得分:1)

Eloquent没有一个内置功能来执行此操作。但是,您可以使用mapModel个对象的集合展平为数组:

$coll = Model::select('id')->where('type', 'user')->get();

// Pull the id out of each member of the collection
$coll = $coll->map(function ($item, $key) {
    return $item->id;
});

// Convert collection to an array
print_r($coll->toArray());