簡體   English   中英

Laravel雄辯的結果收集

[英]Laravel eloquent result to collections

我有一個溫度列表,每n分鍾記錄一次。 我想獲取特定日期的最小ID和最大ID。 $listDate是數組中日期的列表。 例如。

public getTemperature() {
    $listDate = ['2016-12-08','2016-12-09','2016-12-10','2016-12-11'];    
    foreach($listDate as $date) {

        $getId = array();
        $getId[] = $this->selectRaw('MIN(`id`) as min, MAX(`id`) as max')
            ->where('created_at', '>=', $date. ' 00:00:00')
            ->where('created_at', '<=', $date. ' 23:59:59')
            ->get();
    }
    return $getId;
}

我希望它像這樣的收藏回來

['min' => 1123, 'max' => 1345],
['min' => 1349, 'max' => 1567],
['min' => 1589, 'max' => 1612],
['min' => 1624, 'max' => 1655],

每次您遍歷列表時,都將$getId設置為一個空數組。

嘗試這個

public getTemperature() {
    $listDate = ['2016-12-08','2016-12-09','2016-12-10','2016-12-11']; 
    $getId = array();   
    foreach($listDate as $date) {            
        $result = $this->selectRaw('MIN(`id`) as min, MAX(`id`) as max')
                                        ->where('created_at', '>=', $date. ' 00:00:00')
                                        ->where('created_at', '<=', $date. ' 23:59:59')
                                        ->get()->toArray();
        array_push($getId, $result);
    }
    return $getId;
}

您只需要在循環外部定義數組:

public getTemperature() {
    $listDate = ['2016-12-08','2016-12-09','2016-12-10','2016-12-11'];  

    $getId = []; //Define the array here

    foreach($listDate as $date) {
        $getId[] = $this->selectRaw('MIN(`id`) as min, MAX(`id`) as max')
            ->where('created_at', '>=', $date. ' 00:00:00')
            ->where('created_at', '<=', $date. ' 23:59:59')
            ->get();
    }
    return $getId;
}

由於如您的OP中所寫,循環將在每次迭代中初始化數組。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM