0
我試圖簡化下面的查詢。我有一個儀表和一個關係(+或 - ),我想根據儀表標準對日期範圍進行求和。積極的米應該總結,並從總和中減去負數。如下所示,我將儀表數組分爲兩個數組($ meter_plus,$ meter_minus),其中只有id,兩者都用於求和值,但應減去$ 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:點 - 儀表關係
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
這工作得很好,但我想
- 提高查詢
- 計算最終總和在查詢
謝謝!我得到了一系列混合在一起的米。我將它們分成$ meter_plus和$ meter_minus來檢索數據。所以,我創建了新的數組,並使用collect([..])http://laravel.com/docs/5.0/collections轉換它們以使用 - > lists()方法。我對加號和減號數據的結果感興趣,所以你建議 - > get(),這將返回一個數組,我是否正確? – wiesson 2015-02-25 06:57:53
不可以。如果你想在一個查詢中同時使用這兩個數字,你需要使用類似group by的東西,但是在原始查詢中可能會更好地完成檢索meter_I'd數組。 – Anthony 2015-02-25 07:06:46
我已經添加了一些信息,也許他們對你有幫助:) – wiesson 2015-02-25 08:13:17