QueryService.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. class QueryService
  5. {
  6. public static function amount(string $table, string $title)
  7. {
  8. return DB::table($table)
  9. ->selectRaw(
  10. "COUNT(*) AS amount,
  11. (SELECT COUNT(*) FROM products WHERE DATE(updated_at) = CURDATE()) AS amountToday"
  12. )
  13. ->get()
  14. ->transform(
  15. fn($sale) => [
  16. "title" => $title,
  17. "amount" => $sale->amount,
  18. "amountToday" => $sale->amountToday,
  19. ]
  20. )
  21. ->first();
  22. }
  23. public static function statistic(string $table)
  24. {
  25. return DB::table($table)
  26. ->selectRaw(
  27. "COUNT(*) AS amount,
  28. DATE_FORMAT(created_at, '%b') AS month"
  29. )
  30. ->groupByRaw("MONTH(created_at)")
  31. ->get()
  32. ->pluck("amount", "month");
  33. }
  34. public static function statisticDualYear(string $table, string $tableJoin)
  35. {
  36. return DB::table($table)
  37. ->selectRaw(
  38. "DATE_FORMAT($table.created_at, '%Y') AS year,
  39. DATE_FORMAT($table.created_at, '%b') AS month,
  40. IF(
  41. $tableJoin.ppn,
  42. $table.price + $table.price * ((
  43. SELECT
  44. ppn
  45. FROM
  46. ppns) / 100),
  47. $table.price
  48. ) AS price,
  49. COUNT(*) AS total"
  50. )
  51. ->join(
  52. $tableJoin,
  53. "$tableJoin.number",
  54. "=",
  55. "$table.purchase_number"
  56. )
  57. ->groupByRaw(
  58. "YEAR($table.created_at),
  59. MONTH($table.created_at),
  60. year,
  61. month,
  62. price
  63. DESC"
  64. )
  65. ->get();
  66. }
  67. }