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

Ivandokov's avatar

belongsToThrough equivalent or hasManyThrough using pivot table autoincrement key

It is really hard to define a good title for this question...

I am having hard time defining a specific relationship with the following tables:

Schema

Let me first explain the tables.

There are many studios. Each Studio says what type of classes it has with price, duration, etc. Each Instructor can create new classes in a studio "X" by selecting the currently available class types with their existing price, duration, etc.

Note: class_types table holds all possible sports. By "currently available class types" I mean the studios_classes table where the Studio define what classes it has for the studio.

I want from the Class model (which I named ClassModel because "class" is reserved PHP word) to be able to access the Studio. This has to be done through StudioClass model that I used as pivot model for studios_classes table.

Obviously one class can belong to a single studio and hasManyThrough is not convenient in this case.

I defined the other side of the relation for a Studio having many ClassModel as follows and it is working properly:

class Studio extends Model
{
    public function classes()
    {
        return $this->hasManyThrough(ClassModel::class, StudioClass::class, null, 'studio_class_id');
    }
}
0 likes
7 replies
Vilfago's avatar

Why didn't you put all information you had currently in studio_classes table in classes table, and just add "studio_id" in classes table.

And then, you just have a "belongsTo" relation between ClassModel and Studio.

Ivandokov's avatar

Maybe I didn't explain the case properly.

The Studio defined what types of classes, their price, duration and available spots it has.

The Instructor creates the real class that the end users can book.

Example:

Studio "X" defines a dance class which costs $50, takes 1 hour and has 20 spots. Instructor "A" says he will take this class next Wednesday and defines a name for the class that the end users will see.

I know it is a little bit unusual case for a Studio - Instructor - Class relation.

Vilfago's avatar

I don't see how you can set a direct relation between Studio and Class, however you can retrieve data with nested eager loading.

Ivandokov's avatar

I got the SQL query working, but can't seem to make it work with Eloquent relations.

Can you please give me an example of the nested eager loading that you're talking about.

Ivandokov's avatar

Vilfago, thank you! It's not like I don't know what nested eager loading is but haven't thought to use it here. This is what I am going to use.

Please or to participate in this conversation.