mardi 22 décembre 2015

Triple Pivot Challenge

I have the following challenge, trying to join 3 tables in Laravel 5:

I have a many-to-many relation between 3 table: students, classrooms, terms. I would love to make a call like term->classroom->students.

I saw the Eloquent-triple-pivot package, but unfortunately, I cant get it working for Laravel 5.

Please, I would appreciate solution to bind this and make the call, eloquent or otherwise.

Thank you.

EDIT:

I have many-to-many relationship between 3 tables; classrooms, students, terms.

I have 3 pivot tables: classroom_term, classroom_student, student_term.

And 3 corresponding models: ClassroomTerm, ClassroomStudent, StudentTerm.

My Classroom model:

 public function students()
{
    return $this->belongsToMany('App\Student')->withTimestamps();
}
public function terms()
{
    return $this->belongsToMany('App\Term')->withTimestamps();
}

My Term Model:

public function classrooms()
{
    return $this->belongsToMany('App\Classroom')->withTimestamps();
}
public function students()
{
    return $this->belongsToMany('App\Student')->withTimestamps();
}

My Student model:

public function terms()
{
    return $this->belongsToMany('App\Term')->withTimestamps();
}
public function classrooms()
{
    return $this->belongsToMany('App\Classroom')->withTimestamps();
}

What I am doing in my StudentsController is

$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]);

In my students.list view, I would simply want to retrieve students:

@foreach($students as $student)
First Name: {{!!$student->first_name!!}}
@endforeach

The code is cumbersome and not working. Thanks for your help

The Goal: To retrieve the students in the classroom in the term. With many-to-many relationship between classrooms, students and terms.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire