douyong6585 2014-11-07 14:08
浏览 89
已采纳

检索数组而不是key:val(laravel / eloquent)

This query:

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

gives me some ids as a result (structured as key, val)

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

However I only need the ids as an array for this new sum-query:

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

Any eloquent solutions for this? Otherwise I would loop over the key and val array and push they value to a new array. Not that smart?

// edited the question to make it more clear

  • 写回答

3条回答 默认 最新

  • douji9734 2014-11-07 14:26
    关注

    I believe there is a function (its just not in the official docs)

    I found this in the source of 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 ...
    }
    

    So try ->lists('id');

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题