【发布时间】:2015-12-21 11:27:00
【问题描述】:
我有以下挑战,尝试在 Laravel 5 中加入 3 个表:
我在 3 个表之间存在多对多关系:学生、教室、学期。我很想拨打term->classroom->students之类的电话。
我看到了 Eloquent-triple-pivot 包,但不幸的是,我无法让它在 Laravel 5 上运行。
拜托,我会很感激绑定这个并拨打电话的解决方案,无论是雄辩的还是其他的。
谢谢。
编辑:
我在 3 个表之间有 多对多关系;教室、学生、学期。
我有 3 个数据透视表:classic_term、classic_student、student_term。
还有3个对应的模型:ClassroomTerm、ClassroomStudent、StudentTerm。
我的教室模型:
public function students()
{
return $this->belongsToMany('App\Student')->withTimestamps();
}
public function terms()
{
return $this->belongsToMany('App\Term')->withTimestamps();
}
我的术语模型:
public function classrooms()
{
return $this->belongsToMany('App\Classroom')->withTimestamps();
}
public function students()
{
return $this->belongsToMany('App\Student')->withTimestamps();
}
我的学生模型:
public function terms()
{
return $this->belongsToMany('App\Term')->withTimestamps();
}
public function classrooms()
{
return $this->belongsToMany('App\Classroom')->withTimestamps();
}
我在 StudentsController 中所做的是
$term = Term::findOrFail($id);
foreach($term->classrooms as $classroom) {
$studentids = ClassroomStudent::where('classroom_id', '=', $classroom->id)->get();
}
//to get the real student collection
foreach($studentids->student_id as $studentid){
$students = Student::findOrFail($studentid)
}
return view('students.list')->with(['students' => $students]);
在我的 students.list 视图中,我只想检索学生:
@foreach($students as $student)
First Name: {{!!$student->first_name!!}}
@endforeach
错误在这一行:
foreach($studentids->student_id as $studentid){
$students = Student::findOrFail($studentid)
}
Undefined property: Illuminate\Database\Eloquent\Collection::$student_id'
然而 dd($studentids) 返回一个数组,其中一个属性是 student_id。
代码繁琐,无法正常工作。 感谢您的帮助
目标: 检索学期中课堂上的学生。教室、学生和学期之间具有多对多的关系。
【问题讨论】:
-
你遇到什么样的错误?你的代码是什么..?因为你不能简单地做
term->classroom->students你首先做term->classroom通过foreach循环它然后做classroom->students。多对多返回一个数组 -
@Joost 请检查我的 cmets。感谢您的进一步澄清。
-
如果您向我们展示您的表格字段,我们可以为您提供更好的帮助