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

Pankaj's avatar
Level 30

Joining three tables

i have 3 models company, MotorTypes, MotorParts

company -> Many To Many ->MotorTypes and MotorTypes -> hasMany -> MotorParts

i want to relate all these 3 tables like company->MotorTypes->MotorParts

Tried hasManyThrough but it wont work with Many To Many any solution for this ?

0 likes
9 replies
JeroenVanOort's avatar

Last time I did something similar, I used either a foreach or I constructed a join using the query builder, depending on how important performance was.

But, there might be better ways to do this.

JarekTkaczyk's avatar

@pankaj No, there's no relation for this.

Describe what you want to achieve exactly and I'll tell you how.

Pankaj's avatar
Level 30

@JarekTkaczyk company has many motortype and motorparts are specific to motortype so i want to get company's specific motortype ($this->belongsToMany('MotorType'); ) and its motorpart ( motorpart of motortype's returned by above relation )

same as Has Many Through but it has Many To Many relationship( motorType and MotorParts )

Pankaj's avatar
Level 30

or for example @JarekTkaczyk

Student belongsToMany Semesters ( Inverse : Semester belongsToMany Students ) and Semesters hasMany Subjects ( Inverse : A Subject belongsTo Semester )

i want to get student's subject ( via their semester )

JarekTkaczyk's avatar

@pankaj

The easiest way for a specific company:

Company::with(['motorTypes.motorParts' => function ($q) use (&$parts) {
    $parts = $q->get()->unique();
}])->find($companyId);

if you have already fetched $company, then use $company->load(...) instead of with.

Pankaj's avatar
Level 30

@JarekTkaczyk but wat would be database table structure for tat ?? how should i relate both (company and motorTypes) in MotorParts ?? i should add company_id and motortype_id in motorPart table ??

i tried ur above soln but it gives motorPart of which it doesnt belong to company( It should belong both to company and Motortype)

Ex : abcpart belongs to car and company1(both)

JarekTkaczyk's avatar

@pankaj You must describe it better. You have belongsToMany -> hasMany and with this the code will work.

Do you want to associate parts with companies as well or get parts of the company through types?

Please or to participate in this conversation.