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

图片转代码服务由CSDN问答提供 功能建议

此查询:

  $ ids = EnergyMeters :: leftJoin  ('meteringpoint_energymeter_relation','energymeter.id','=',
'meteringpoint_energymeter_relation.meterId')
  - &gt; where('id','=',$ meterPointId)
  - &gt; where('已删除 ',''','0')
  - &gt; select('energymeter.id')
  - &gt; orderBy('name')
  - &gt; get(); 
  <  / pre> 
 
 

给我一​​些id作为结果(结构为key,val)

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

但是我只需要将id作为这个新求和查询的数组:

  Data :: select(array(DB :: RAW('sum(v1)  )作为sumV1','sum(v2)作为sumV2')))
  - &gt; whereIn('id',$ ids)
  - &gt; where('PointOfTime','&gt;',$ from)\  n  - &gt; where('PointOfTime','&lt; =',$ to + 86400)
  - &  gt; get(); 
   
 
 

任何雄辩的解决方案? 否则我会遍历key和val数组并将它们的值推送到一个新数组。 不那么聪明吗?

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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条)

相关推荐 更多相似问题