Ad
Laravel: Eloquent 5 Tables In 1 Query
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.
- student
- schedule
- schedule_student
student_id,schedule_id
- activity
schedule_id
- scores
student_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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad