Bez popisu

Semester.php 2.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App;
  3. use Exception;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Semester extends Model
  6. {
  7. public $primaryKey = 'code';
  8. public $incrementing = false;
  9. public $timestamps = false;
  10. protected $keyType = 'string';
  11. protected $fillable = [
  12. 'code',
  13. 'alpha'
  14. ];
  15. public function courses() {
  16. return $this->belongsToMany(Course::class, 'sections');
  17. }
  18. public function sections() {
  19. return $this->hasMany(Section::class);
  20. }
  21. public function professors() {
  22. return $this->belongsToMany(Professor::class)->withPivot('admin_load', 'investigative_load');
  23. }
  24. public function getIsFutureAttribute() {
  25. return Semester::orderBy('code', 'desc')->take(6)->get()->contains('code', $this->code);
  26. }
  27. /**
  28. * Returns a clone of this semester with the provided code and alpha.
  29. * This functions also copies every section and professor_section
  30. *
  31. * @param string $newSemCode
  32. * @param string $newSemAlpha
  33. * @param int $dept_id
  34. *
  35. * @return Semester
  36. */
  37. public function clone(string $newSemCode, string $newSemAlpha, int $dept_id) {
  38. // if (Semester::find($newSemCode)) {
  39. // throw new Exception('A semester with code ' . $newSemCode . ' already exists');
  40. // }
  41. $semClone = Semester::firstOrCreate(
  42. ['code' => $newSemCode],
  43. ['alpha' => $newSemAlpha],
  44. );
  45. $this->loadMissing([
  46. 'sections' => function ($query) use ($dept_id) {
  47. $query->select('sections.id', 'course_id', 'semester_code', 'sections.code', 'student_count', 'sections.syllabus', 'credits', 'quota')
  48. ->join('courses', 'courses.id', '=', 'sections.course_id')
  49. ->where('dept_id', '=', $dept_id);
  50. },
  51. 'sections.professors',
  52. 'sections.schedules'
  53. ]);
  54. // Copy all sections to new semester
  55. foreach($this->sections as $section) {
  56. $sectionClone = $section->replicate();
  57. $sectionClone->semester_code = $semClone->code;
  58. $existingSection = Section::where([['semester_code', '=', $sectionClone->semester_code], ['course_id', '=', $sectionClone->course_id], ['code', '=' , $sectionClone->code]])->first();
  59. if (!$existingSection) {
  60. $sectionClone->save();
  61. foreach($section->professors as $professor) {
  62. $sectionClone->professors()->attach($professor, ['percent' => $professor->pivot->percent]);
  63. }
  64. foreach($section->schedules as $schedule) {
  65. $scheduleClone = $schedule->replicate();
  66. $scheduleClone->section_id = $sectionClone->id;
  67. $scheduleClone->save();
  68. $sectionClone->schedules()->save($scheduleClone);
  69. }
  70. }
  71. }
  72. return $semClone;
  73. }
  74. }