Nenhuma descrição

Semester.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. *
  34. * @return Semester
  35. */
  36. public function clone(string $newSemCode, string $newSemAlpha) {
  37. if (Semester::find($newSemCode)) {
  38. throw new Exception('A semester with code ' . $newSemCode . ' already exists');
  39. }
  40. $newSem = Semester::create([
  41. 'code' => $newSemCode,
  42. 'alpha' => $newSemAlpha,
  43. ]);
  44. // Copy all sections to new semester
  45. foreach($this->sections as $section) {
  46. $sectionClone = $section->replicate();
  47. $sectionClone->semester_code = $newSem->code;
  48. $sectionClone->save();
  49. foreach($section->professors as $professor) {
  50. $sectionClone->professors()->attach($professor, ['percent' => $professor->pivot->percent]);
  51. }
  52. foreach($section->schedules as $schedule) {
  53. $sectionClone->schedules()->save($schedule);
  54. }
  55. }
  56. return $newSem;
  57. }
  58. }