簡體   English   中英

計算按日期分組的2個不同表的條目並合並Laravel 4.2中的結果

[英]Count entries of 2 different tables grouped by date and combine results in Laravel 4.2

我想知道如何計算按日期分組的兩個不同表的條目數,然后在Laravel 4.2中將2個結果集合並為1個結構?

表1(車手)

|  id  |  rider  |  created_at           |
|  1   |  james  |  2017-08-27 03:01:22  |
|  2   |  clara  |  2017-05-27 06:32:33  |
|  3   |  john   |  2017-04-27 09:54:32  |
|  4   |  ken    |  2017-04-27 09:54:32  |

表2(驅動程序)

|  id  |  driver  |  created_at           |
|  1   |  Karlie  |  2017-08-27 03:01:22  |
|  2   |  Doe     |  2017-03-27 06:32:33  |
|  3   |  Mike    |  2017-02-27 09:54:32  |

我想要這樣的輸出:

|  created_at  |  rider entries  |  driver entries  |
|  2017-02-27  |  0              |  1               |
|  2017-03-27  |  0              |  1               |
|  2017-04-27  |  2              |  0               |
|  2017-05-27  |  1              |  0               |
|  2017-08-27  |  1              |  1               |

您可以使用查詢生成器從每個表中獲取計數(請參閱https://laravel.com/docs/4.2/queries中的文檔),但是要組合它們,您將不得不循環。

您的代碼可能看起來像這樣:

// Get the counts for riders table
$riders = DB::table('Table1')
                ->groupBy('created_at')
                ->count();

// Get the counts for drivers table
$drivers = DB::table('Table2')
                ->groupBy('created_at')
                ->count();

// An associative array to hold our final result
$combined = [];

// Loop over riders, adding them to the combined array
foreach( $riders as $rider ){
    // Array keys have to start with a letter
    $key = 'd' . $rider->created_at->format('Y-m-d');
    $combined[$key]['created_at'] = $rider->created_at->format('Y-m-d');
    $combined[$key]['rider_entries'] = $rider->count;
}

// Loop over drivers, adding them to the combined array
foreach( $drivers as $driver ){
    $key = 'd' . $driver->created_at->format('Y-m-d');
    $combined[$key]['created_at'] = $driver->created_at->format('Y-m-d');
    $combined[$key]['driver_entries'] = $driver->count;
}

// Finally, iterate over the result, filling in zero values
foreach( $combined as $c ){
    if( !isSet($c['rider_entries']) ){
        $c['rider_entries'] = 0;
    }
    if( !isSet($c['driver_entries']) ){
        $c['driver_entries'] = 0;
    }
}

dd( $combined );

注意:我尚未測試此代碼,但我希望它能幫助您了解如何最好地實現它。

暫無
暫無

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

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