SupaMonkey
SupaMonkey

Reputation: 884

Laravel filter parent

This seems easy enough in my mind, but I think I've been at this for too long.

Structure:

Student
|_Bursaries
  |_Enrolments
    |_Courses

Academic Institution
|_Campus

An Enrolment also gets assigned a Campus.

What I'm trying to achieve is to find the enrolment that has an Academic Institution with the name 'Pearson Institute' (in this case) so that I can create a course under the found enrolment. (If no enrolment is found with such an Academic Institution, then I would create it).

            $student = Student::findOrFail(1); // select the student I want to work with
            $bursary = $student->bursaries()->first(); // select the first bursary
            $bursary->enrolments()->whereHas('academic_institution', function (Builder $query) {
                $query->where('academic_institution','=','Pearson Institute');
            })->get(); //select the academic institution - here is where its going wrong.

I think I am misunderstanding/misusing whereHas?

Enrolment model:

class StudentBursaryEnrolment extends Model
{
protected $fillable = [
    'academic_institution_campus_id',
    'student_number'
];

public function student () {
    return $this->belongsTo('App\Student');
}

public function academic_institution () {
    return $this->hasOneThrough('App\AcademicInstitution','App\AcademicInstitutionCampus');
}

public function academic_institution_campus () {
    return $this->belongsTo('App\AcademicInstitutionCampus');
}

public function courses() {
    return $this->hasMany('App\StudentBursaryEnrolmentCourse');
}
}

Upvotes: 0

Views: 121

Answers (1)

JorisJ1
JorisJ1

Reputation: 989

How about this; find the institution before querying enrolments:

$institution = AcademicInstitution::where('academic_institution', 'Pearson Institute')
    ->first();

if (!is_null($institution)) {
    $enrolments = $bursary->enrolments()
        ->where('academic_institution', $institution->id)
        ->get();
}

An alternative might be a ->join(), but the above is less complex.


As a side note: I find your datalayout unclear and I suggest you redesign it. For instance, is a bursary really mandatory for a student to enroll? And StudentBursaryEnrolmentCourse feels like it should not be a model at all but a pivot table instead.

Something like this (for a start):

  • Student hasMany Bursary.

  • Student hasMany Enrolment.

  • Enrolment belongsTo Student.

  • Student hasMany Course.

  • AcademicInstitution hasMany Enrolment.

  • Enrolment belongsTo AcademicInstitution.

Upvotes: 1

Related Questions