我有一个学校模型,其中有许多学生模型谁参加了多个课程模型,我也有一个控制器为每个。
我需要能够访问学校类型(大、小等),无论我是在学生、课程还是学校控制器中。
在一个严格的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这样的学生模型来获取schoolType,还是应该更像$lesson->student->school->schoolType,这样课程就不会直接与学生相关?
发布于 2018-01-25 00:52:26
使用eloquent relationship 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;如果你想直接从课程中访问schoolType -
$lession = Lession::find($lession_id);
$schoolType = $lession->school->schoolType;https://stackoverflow.com/questions/48427620
复制相似问题