检索一个数组而不是关键字:val(laravel/雄辩)


retrieve an array instead of key:val (laravel / eloquent)

此查询:

$ids = EnergyMeters::leftJoin('meteringpoint_energymeter_relation', 'energymeter.id', '=', 
'meteringpoint_energymeter_relation.meterId')
                    ->where('id', '=', $meterPointId)
                    ->where('Deleted', '=', '0')
                    ->select('energymeter.id')
                    ->orderBy('name')
                    ->get();

结果给了我一些ID(结构化为密钥,val)

[{"id":"03cd0c39-a51c-41a0-bbe3-37ae641d051e"},{"id":"0ebf61e7-b751-4931-b737-d8f71297e499"}, {"id"}, '...']

然而,我只需要id作为这个新的总和查询的数组:

Data::select(array(DB::RAW('sum(v1) as sumV1', 'sum(v2) as sumV2')))
            ->whereIn('id', $ids)
            ->where('PointOfTime', '>', $from)
            ->where('PointOfTime', '<=', $to + 86400)
            ->get();

对此有什么雄辩的解决方案吗?否则,我会循环遍历key和val数组,并将它们的值推送到一个新数组。不是那么聪明吗?

//编辑了问题以使其更加清晰

对第一个查询结果集使用;

$data = Data::select(array(DB::RAW('sum(v1) as sumV1', 'sum(v2) as sumV2')))
        ->whereIn('id', $ids)
        ->where('PointOfTime', '>', $from)
        ->where('PointOfTime', '<=', $to + 86400)
        ->get();
$ids = $data->lists('id');

请注意lists('id'),这将为您提供所需的数组。然后,您可以将结果传递到另一个查询中。

"列表"已重命名为"提取"

https://laravel.com/docs/5.6/queries#retrieving-结果显示:

检索列值列表如果要检索包含单列值的集合,可以使用拔毛法。在本例中,我们将检索角色的集合标题:

$titles = DB::table('roles')->pluck('title');
foreach ($titles as $title) {
    echo $title;
}

我相信有一个函数(它只是不在官方文档中)

我在Laravel的来源中发现了这一点:

/**
 * Get an array with the values of a given column.
 *
 * @param  string  $column
 * @param  string  $key
 * @return array
 */
public function lists($column, $key = null)
{
    // ... lots of code ...
}

所以尝试->lists('id');