Support the ongoing development of Laravel.io →
Database Eloquent

Hello, I'm Developing a system for displaying a list of mandatories done by a student in a specified Course

http://laravel.io/bin/yLv13

Example Output:

##Course: ###Student[0] ####Course.Mandatory[0] ####Course.Mandatory[1] ###Student[1] ####Course.Mandatory[0] ###Student[2] ####Course.Mandatory[0]

I have multiple Courses and the problem is that my "with" sencente in the Eloquent returns ALL mandatories instead of those with the Course id of $course.

How would i do this? is it even possible to do with Eloquent?

Tables:

##Course: |id|CourseId|CourseName| ##Student: |id|studentId ##Mandatory: |id|name|fk_course| ##Student_Course: |id|fk_student|fk_course| # M2M ##Student_Mandatory: |id|fk_student|fk_mandatory| #M2M

I have models for all of these tables (except M2M)

Anyone have a idea?

Last updated 3 years ago.
0

I think another table is needed. I don't have any inspiration right now for the name, lets call it X. :D

Then

A student has many X,

A X belongs to a course,

A X has and belongs to many mandatories.

This way :

foreach($student->x as $x){

  foreach($x->mandatories as $mandatory){

    echo $x->course->name . ' - ' . $mandatory->name;

  }

}

Then you can remove students/courses M2M relationship and replace it by a has many through relationship (through X)

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

perara perara Joined 1 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.