1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
-
- namespace App;
-
- use Exception;
- use Illuminate\Database\Eloquent\Model;
-
- class Semester extends Model
- {
- public $primaryKey = 'code';
- public $incrementing = false;
- public $timestamps = false;
-
- protected $keyType = 'string';
- protected $fillable = [
- 'code',
- 'alpha'
- ];
-
-
- public function courses() {
- return $this->belongsToMany(Course::class, 'sections');
- }
-
- public function sections() {
- return $this->hasMany(Section::class);
- }
-
- public function professors() {
- return $this->belongsToMany(Professor::class)->withPivot('admin_load', 'investigative_load');
- }
-
- public function getIsFutureAttribute() {
- return Semester::orderBy('code', 'desc')->take(6)->get()->contains('code', $this->code);
- }
-
- /**
- * Returns a clone of this semester with the provided code and alpha.
- * This functions also copies every section and professor_section
- *
- * @param string $newSemCode
- * @param string $newSemAlpha
- * @param int $dept_id
- *
- * @return Semester
- */
- public function clone(string $newSemCode, string $newSemAlpha, int $dept_id) {
- // if (Semester::find($newSemCode)) {
- // throw new Exception('A semester with code ' . $newSemCode . ' already exists');
- // }
- $semClone = Semester::firstOrCreate(
- ['code' => $newSemCode],
- ['alpha' => $newSemAlpha],
- );
-
- $this->loadMissing([
- 'sections' => function ($query) use ($dept_id) {
- $query->select('sections.id', 'course_id', 'semester_code', 'sections.code', 'student_count', 'sections.syllabus', 'credits', 'quota')
- ->join('courses', 'courses.id', '=', 'sections.course_id')
- ->where('dept_id', '=', $dept_id);
- },
- 'sections.professors',
- 'sections.schedules'
- ]);
- // Copy all sections to new semester
- foreach($this->sections as $section) {
- $sectionClone = $section->replicate();
- $sectionClone->semester_code = $semClone->code;
- $existingSection = Section::where([['semester_code', '=', $sectionClone->semester_code], ['course_id', '=', $sectionClone->course_id], ['code', '=' , $sectionClone->code]])->first();
- if (!$existingSection) {
- $sectionClone->save();
-
- foreach($section->professors as $professor) {
- $sectionClone->professors()->attach($professor, ['percent' => $professor->pivot->percent]);
- }
-
- foreach($section->schedules as $schedule) {
- $scheduleClone = $schedule->replicate();
- $scheduleClone->section_id = $sectionClone->id;
- $scheduleClone->save();
- $sectionClone->schedules()->save($scheduleClone);
- }
- }
- }
-
- return $semClone;
- }
-
- }
|