【问题标题】:Dependencies between School, Student and Lesson models学校、学生和课程模型之间的依赖关系
【发布时间】:2018-07-03 19:14:30
【问题描述】:

我有一个 School 模型,其中有许多学生模型参与多个课程模型,我也为每个模型设置了一个控制器。

我需要能够访问学校类型(大、小等),无论我是在学生、课程还是学校控制器中。

这种方法在严格的 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));
    }
}

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

我的意思是,我应该通过像 $lesson->school->schoolType 这样的 Student 模型获得 schoolType,还是应该更像 $lesson->student->school->schoolType,所以课程与学生没有直接关系?

【问题讨论】:

    标签: laravel oop model-view-controller model controller


    【解决方案1】:

    使用雄辩的关系hasManybelongsTo

    在您的学校模型中-

    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;
    

    如果你想直接从课程中访问schoolType-

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

    【讨论】:

    • 那么,如果我正在处理的课程尚未分配给任何学生,我如何从课程模型中访问 schoolType?
    • 你不能,因为课程和学校之间没有关系,你只能在有学生参与的情况下,这是你在问题中指定的,对吧??
    • 但是从课程管理员那里我需要知道我在哪所学校。
    • 那么你需要在 Lesson 模型中创建一个额外的 belongsTo 关系,比如 belongsTo student。
    猜你喜欢
    • 2020-06-24
    • 2019-07-11
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多