2024_05_24_234032_site_data_flow.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. use App\Models\NodeDailyDataFlow;
  3. use Carbon\Carbon;
  4. use Illuminate\Database\Migrations\Migration;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Facades\Schema;
  7. return new class extends Migration
  8. {
  9. /**
  10. * Run the migrations.
  11. */
  12. public function up(): void
  13. {
  14. Schema::table('node_daily_data_flow', static function (Blueprint $table) {
  15. $table->unsignedInteger('node_id')->nullable()->change();
  16. });
  17. // 使用查询构建器对数据进行分组并计算合计值
  18. $dailyTotals = NodeDailyDataFlow::whereNotNull('node_id')->oldest()->selectRaw('DATE(created_at) as date, SUM(u) as total_u, SUM(d) as total_d')
  19. ->groupBy('date')
  20. ->get();
  21. // 遍历查询结果,创建新的合计列
  22. foreach ($dailyTotals as $dailyTotal) {
  23. // 创建新记录,同时设置合计列的初始值
  24. NodeDailyDataFlow::create([
  25. 'u' => $dailyTotal->total_u,
  26. 'd' => $dailyTotal->total_d,
  27. 'created_at' => Carbon::parse($dailyTotal->date)->endOfDay(),
  28. ]);
  29. }
  30. }
  31. /**
  32. * Reverse the migrations.
  33. */
  34. public function down(): void
  35. {
  36. NodeDailyDataFlow::whereNull('node_id')->delete();
  37. Schema::table('node_daily_data_flow', static function (Blueprint $table) {
  38. $table->unsignedInteger('node_id')->nullable(false)->change();
  39. });
  40. }
  41. };