我有三个表学生,课程和成绩。
和年级有两个外键: student_id 和 course_id ,它属于两个表。
C:\whatever\path\to\myMavenRepo\foo\bar\baz\1.0.0\baz-1.0.0.jar
另外,学生和课程有很多年级:
class Grade extends Model
{
public function student()
{
return $this->belongsTo('App\Student');
}
public function course()
{
return $this->belongsTo('App\Course');
}
}
和
class Student extends Model
{
public function grades()
{
return $this->hasMany('App\Grade');
}
}
现在,我想在学生和课程之间建立关系,例如,对于Student1,我想检索所有具有分数的课程。像这样的东西,但这是不正确的:
class Course extends Model
{
public function grades()
{
return $this->hasMany('App\Grade');
}
}
我可以简单地写
$student1->grades->course
但是我不想要它,我想在我的foreach循环中加入@foreach($student1->grades as $grade)
$grade->course
@endforeach
。
答案 0 :(得分:2)
我建议您引用https://laravel.com/docs/5.8/eloquent-relationships#has-many-through链接以实现此目的,
在学生模式中添加 hasManyThrough 关系。
public function courses()
{
return $this->hasManyThrough(
'App\Course',
'App\Grade',
'course_id', // Foreign key on Grade table...
'id', // Foreign key on Course table...
'id', // Local key on Student table...
'student_id' // Local key on Grade table...
);
}
我没有测试这段代码,但这是这种方式
答案 1 :(得分:2)
将成绩表设置为 PIVOT表,以了解学生和课程之间的多对多关系。
class Student
{
// an alternative name could be gradedCourses.
public function courses()
{
return $this->belongsToMany(Course::class, 'grades');
}
}
因此您可以直接通过这种关系访问课程。
@foreach($student->courses course)
$course->name
@endforeach