Ad

Laravel: Eloquent 5 Tables In 1 Query

- 1 answer

I have a 5 tables and i want this to be in the form of eloquent. How do i combine all tables using the with(), or their are other ways to do this.

  1. student
  2. schedule
  3. schedule_student student_id,schedule_id
  4. activity schedule_id
  5. scoresstudent_id, activity_id,score

My Models

//Activity
    public function schedule()
    {
        return $this->belongsTo(Schedule::class);
    }
    public function students()
    {
        return $this->belongsToMany(Student::class,'scores');
    }

//Student

    public function schedules()
    {
        return $this->belongsToMany(Schedule::class,'schedule_student');
    }
    public function activities()
    {
        return $this->belongsToMany(Activity::class,'scores');
    }

//Schedule
    public function activities()
    {
        return $this->hasmany(Activity::class);
    }
    public function students()
    {
        return $this->belongsToMany(Student::class,'schedule_student');
    }

//Student
    public function student()
    {
        return $this->belongsTo(Student::class);
    }
    public function activity()
    {
        return $this->belongsTo(Activity::class);
}

How do i combine all 4 tables(except schedule_student) so the json will look like from below:

schedule[] 
   =>activities[]
         =>students[]
               =>scores[]
Ad

Answer

You can use nested with relation, try something like :

$schedules = Schedule::with('activities', 'students', 'activities.scores')->get();

Honestly, I understand nothing to your data model, I think you mixed some titles and models. But in the global idea, you can use nested relations using a dot (.).

Ad
source: stackoverflow.com
Ad