QueryService.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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(created_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. ->whereRaw("YEAR(created_at) = YEAR(CURDATE())")
  41. ->groupByRaw("month")
  42. ->orderByRaw("created_at")
  43. ->get()
  44. ->pluck("amount", "month");
  45. }
  46. public static function priceStatistic(string $table)
  47. {
  48. return DB::table($table)
  49. ->selectRaw(
  50. "price,
  51. created_at"
  52. )
  53. ->orderByRaw("created_at")
  54. ->get()
  55. ->groupBy([
  56. fn($value) => Carbon::parse($value->created_at)->format("Y"),
  57. fn($value) => Carbon::parse($value->created_at)->format("M"),
  58. ])
  59. ->take(2)
  60. ->transform(
  61. fn($year) => $year->transform(
  62. fn($month) => $month->sum(fn($arr) => $arr->price)
  63. )
  64. );
  65. }
  66. }