代码之家  ›  专栏  ›  技术社区  ›  human

学校、学生和课程模型之间的依赖关系

  •  2
  • human  · 技术社区  · 8 年前

    我有一个学校模型,其中有许多学生模型,他们参与多个课程模型,我还为每个模型配备了一个控制器。

    我需要能够访问学校类型(大型、小型等),无论我是学生、班级还是学校管理员。

    在严格的OOP环境中,这种方法正确吗?

    // School model
    class School
    {
        ...
    
        public getSchoolType()
        {
            return $this->schoolType;
        {
    
    }
    
    // Student model
    class Student
    {
        ...
    
        public school()
        {
            return $this->school;
        {
    
    }
    
    // Lesson model
    class Lesson
    {
        ...
    
        public student()
        {
            return $this->student;
        {
    
    }
    
    // Student controller 
    class StudentController
    {
        public function show(Student $student)
        {
            $schoolType = $student->school->schoolType;
            return view('students', array($schoolType));
        }
    }
    
    // Lesson controller 
    class LessonController
    {
        public function show(Lesson $lesson)
        {
            $schoolType = $lesson->student->school->schoolType;
            return view('lessons', array($schoolType));
        }
    }
    

    如果课程以多对多的方式与学生相关,如果没有学生参加该课程,如何在课程控制器中获取学校类型?

    我的观点是,我真的应该通过学生模型得到学校类型吗 $lesson->school->schoolType 或者应该更像 $lesson->student->school->schoolType ,那么课程与学生没有直接关系?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Sohel0415    8 年前

    使用雄辩的关系 hasMany belongsTo .

    在您的学校模型中-

    public function students()
    {
        return $this->hasMany(Student::class);
    }
    

    在你的学生模型中-

    public function lessons()
    {
        return $this->hasMany(Lesson::class);
    }
    public function school()
    {
        return $this->belongsTo(School::class);
    }
    

    在您的课程模型中-

    public function student()
    {
        return $this->belongsTo(Student::class);
    }
    public function school()
    {
        return $this->belongsTo(School::class);
    }
    

    现在您可以轻松访问 schoolType 因为您可以使用此 relationship . 例如 Lesson Controller -

    $lession = Lession::find($lession_id);
    $schoolType = $lession->student->school->schoolType;
    

    如果要访问 学校类型 直接来自课程-

    $lession = Lession::find($lession_id);
    $schoolType = $lession->school->schoolType;