雄辩简化/组合查询

时间:2015-02-24 13:18:33

标签: mysql laravel eloquent

我正在尝试简化以下查询。我有一个仪表和一个关系(+或 - ),我想根据仪表标准总结日期范围。积分表应该总结,负数表从总和中减去。如下所示,我将仪表阵列分成两个数组($ meter_plus,$ meter_minus),只有ids,两者都是和值,但是应该减去$ meter_minus。

//编辑:获取米

$begin = new \DateTime($from);
$end = new \DateTime($to);
$end = $end->modify('+1 day');
// find points and meters by group
$grouping = App\Grouping::with('points.meters')->find($group_id);
$meter_plus = [];
$meter_minus = [];
// each group has one-to-many points, each point has one-to-many meters
foreach($grouping->points as $point) {
    foreach($point->meters as $meter) {
        if($meter->Relation == '+') {
            array_push($meter_plus, $meter);
        } else {
            array_push($meter_minus, $meter);
        }
    }
}

// Edit2:Point - Meter relation

public function meters()
{
    return $this->belongsToMany('App\EnergyMeter', 'meteringpoint_energymeter_relation', 'point_id', 'meter_id')
        ->whereHas('users', function ($q) {
            $q->where('UserID', Auth::id());
        })
        ->where('Deleted', 0)
        ->select('*', 'meteringpoint_energymeter_relation.Relation')
        ->orderBy('EMNumber');
}

-

$plus = Data::selectRaw('sum(values) as data')
    ->where('PointOfTime', '>', $begin->format('U'))
    ->where('PointOfTime', '<=', $end->format('U'))
    ->whereIn('meter_id', collect($meter_plus)->lists('id'))
    ->first();

$minus = Data::selectRaw('sum(values) as data')
    ->where('PointOfTime', '>', $begin->format('U'))
    ->where('PointOfTime', '<=', $end->format('U'))
    ->whereIn('meter_id', collect($meter_minus)->lists('id'))
    ->first();

$data = $plus->data - $minus->data

这很好但我想

  1. 改进查询
  2. 计算查询中的最终总和

1 个答案:

答案 0 :(得分:0)

whereBetween范围使用PointOfTimesum代替selectRaw。另外,如果$meter_plus已经只是一个ID的数组,那么您不需要做任何与collect相关的事情。您可能还想指出要查询的表。

$plus = Data::table('some_table')
    ->sum('values')
    ->whereBetween('PointOfTime',array($begin->format('U'), $end->format('U')))
    ->whereIn('meter_id', $meter_plus)
    ->sum('values')
    ->get();