Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Cederman's avatar

Problem setting up correct relationship School <-- School Class --> Student

Hi! I have a project I'm working on which is handling event for students. Each event has a school related to it and that school obviously has several school classes, which in turn contains students.

The relationship that I have set up, and which are working are SchoolClass, which belongs to a School, and a SchoolClass belongs to many students (contacts).

The models are as follows (trimmed)...

SchoolClass.php:

<?php

class SchoolClass extends \Eloquent {

    public function school()
    {
        return $this->belongsTo('School');
    }

    public function students()
    {
        return $this->belongsToMany('Contact');
    }

    public function event()
    {
        return $this->belongsTo('StudentEvent');
    }

School.php:

<?php

class School extends \Eloquent {

    public function events()
    {
        return $this->hasMany('StudentEvent');
    }

    public function classes()
    {
        return $this->hasMany('SchoolClass');
    }

    public function students()
    {
        // Don't know how to reach these students
    }

Contact.php (the student):

<?php

class Contact extends \Eloquent {

    public function schoolClass()
    {
        return $this->belongsToMany('SchoolClass');
    }
   public function school()
    {
        // Don't know how to reach this school
    }

The problem I have is how to reach the students from a school as well as reaching the school for a given contact (student). I have seen the hasManyThrough relationship, but in my case the students are connected to a given class by an intermediate table. Since this Contact model object can be a photographer or dj as well.

Am I doing this wrong? Tips are most welcome =)

0 likes
2 replies

Please or to participate in this conversation.