QueryService.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Services;
  3. use Carbon\Carbon;
  4. use Illuminate\Support\Facades\DB;
  5. class QueryService
  6. {
  7. public static function amount(
  8. string $table,
  9. string $title,
  10. string $description
  11. ) {
  12. return DB::table($table)
  13. ->selectRaw(
  14. "COUNT(*) AS amount, (
  15. SELECT
  16. COUNT(*)
  17. FROM
  18. products
  19. WHERE
  20. DATE(updated_at) = CURDATE()) AS amountToday"
  21. )
  22. ->get()
  23. ->transform(
  24. fn($table) => [
  25. "title" => $title,
  26. "amount" => $table->amount,
  27. "amountToday" => $table->amountToday,
  28. "amountTodayDescription" => $description,
  29. ]
  30. )
  31. ->first();
  32. }
  33. public static function amountStatistic(string $table)
  34. {
  35. return DB::table($table)
  36. ->selectRaw(
  37. "COUNT(*) AS amount,
  38. DATE_FORMAT(created_at, '%b') AS month"
  39. )
  40. ->groupByRaw("month")
  41. ->orderByRaw("created_at")
  42. ->get()
  43. ->pluck("amount", "month");
  44. }
  45. public static function priceStatistic(string $table)
  46. {
  47. return DB::table($table)
  48. ->selectRaw(
  49. "price,
  50. created_at"
  51. )
  52. ->orderByRaw("created_at")
  53. ->get()
  54. ->groupBy([
  55. fn($value) => Carbon::parse($value->created_at)->format("Y"),
  56. fn($value) => Carbon::parse($value->created_at)->format("M"),
  57. ])
  58. ->take(2)
  59. ->transform(
  60. fn($year) => $year->transform(
  61. fn($month) => $month->sum(fn($arr) => $arr->price)
  62. )
  63. );
  64. }
  65. }