StudentIdService.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. class StudentIdService
  5. {
  6. /**
  7. * 生成新的学生ID
  8. *
  9. * @return string
  10. */
  11. public static function generateStudentId(): string
  12. {
  13. $timestamp = time();
  14. // 获取当前时间戳下的序号
  15. $sequence = self::getNextSequence($timestamp);
  16. return "stu_{$timestamp}_{$sequence}";
  17. }
  18. /**
  19. * 获取下一个序号
  20. *
  21. * @param int $timestamp
  22. * @return int
  23. */
  24. private static function getNextSequence(int $timestamp): int
  25. {
  26. // 查找相同时间戳的最后一个序号
  27. $lastStudent = DB::table('students')
  28. ->where('student_id', 'like', "stu_{$timestamp}_%")
  29. ->orderByRaw('CAST(SUBSTRING_INDEX(student_id, "_", -1) AS UNSIGNED) DESC')
  30. ->first();
  31. if ($lastStudent) {
  32. // 提取序号并递增
  33. $lastSequence = (int) substr($lastStudent->student_id, strrpos($lastStudent->student_id, '_') + 1);
  34. return $lastSequence + 1;
  35. }
  36. return 0;
  37. }
  38. /**
  39. * 验证学生ID格式是否正确
  40. *
  41. * @param string $studentId
  42. * @return bool
  43. */
  44. public static function validateStudentIdFormat(string $studentId): bool
  45. {
  46. return preg_match('/^stu_\d+_\d+$/', $studentId) === 1;
  47. }
  48. }