Grade.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace addons\exam\controller;
  3. use addons\exam\model\BaseModel;
  4. use addons\exam\model\GradeModel;
  5. use think\Db;
  6. /**
  7. * 试卷考试成绩接口
  8. */
  9. class Grade extends Base
  10. {
  11. protected $noNeedLogin = ['*'];
  12. protected $noNeedRight = ['*'];
  13. /**
  14. * 获取成绩列表
  15. */
  16. public function index()
  17. {
  18. $list = GradeModel::with(
  19. [
  20. // 'user' => BaseModel::withSimpleUser(),
  21. 'cate' => BaseModel::withSimpleCate(),
  22. 'paper' => BaseModel::withSimplePaper(),
  23. ]
  24. )
  25. ->where('user_id', $this->auth->id)
  26. ->order('id desc')
  27. ->paginate(15, true);
  28. $this->success('', compact('list'));
  29. }
  30. /**
  31. * 排行榜
  32. */
  33. public function rank()
  34. {
  35. if (!$paper_id = input('paper_id/d', '0')) {
  36. $this->error('缺少试卷信息');
  37. }
  38. $result = cache_data("rank:paper-{$paper_id}", function () use ($paper_id) {
  39. $grade_count = GradeModel::where('paper_id', $paper_id)->group('user_id')->count();
  40. $pass_count = GradeModel::where('paper_id', $paper_id)->where('is_pass', 1)->group('user_id')->count();
  41. $pass_rate = round(($pass_count / $grade_count) * 100, 2) . '%';
  42. // $pass_rate = bcmul(bcdiv($pass_count, $grade_count, 4), 100, 2) . '%';
  43. if ($grade_count) {
  44. // 子查询,先取出最新的成绩
  45. $subQuery = Db::name('exam_grade')
  46. ->field('id,user_id,cate_id,paper_id,mode,MAX(score) AS score,is_pass,grade_time')
  47. ->where('paper_id', $paper_id)
  48. ->group('user_id')
  49. ->order('id desc')
  50. ->buildSql();
  51. // 再根据成绩、考试时间排序,取出前10名
  52. $list = GradeModel::with(
  53. [
  54. 'user' => BaseModel::withSimpleUser(),
  55. ]
  56. )->table($subQuery . ' exam_grade')
  57. // ->where('paper_id', $paper_id)
  58. // ->group('user_id')
  59. ->order('score desc, grade_time asc')
  60. ->limit(10)
  61. ->select();
  62. } else {
  63. $list = [];
  64. }
  65. return [
  66. 'summary' => [
  67. 'grade_count' => $grade_count,
  68. 'pass_count' => $pass_count,
  69. 'pass_rate' => $pass_rate,
  70. 'cache_time' => datetime(time()),
  71. ],
  72. 'list' => $list,
  73. ];
  74. }, 3600, true);
  75. $this->success('', json_decode($result, true));
  76. }
  77. }