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

SangminKim's avatar

belongsToMany for more than 2 foreign keys?

Hi everyone! I have four tables:

Event  - id, name

Corporation - id, name

Job - id, corporation_id, name

RegisteredJob - id, event_id, corporation_id, job_id.

As you can see, RegisteredJob table has three foreign keys - representing jobs registered for a job fair event. I think I should use belongsToMany for relationships... but the example Laravel documentation is using only two tables.

Has anyone tried belongsToMany with 3 foreign keys? Did it go well or did you find it tricky with all these pivot where... pivot sync... and etc?

If belongsToMany is particularly for two tables with many-to-many relationships only... Should I refactor RegisteredJob table something like the following?

Event  - id, name

Corporation - id, name

Job - id, corporation_id, name

// New table storing corporations attending an event.
RegisteredCorporation - id, event_id, corporation_id.

RegisteredJob - id, registered_corporation_id, event_id, job_id.

The reason why I'm keeping three foreign keys in one table is that it reduces the amount of codes I need to write... for example,

// To find a corporation name and an event name... I need to use nested with functions...
$registered_job = RegisteredJob::with('registered_corporation.corporation')->with('registered_corporation.event')....

// With one table with three foreign keys... I can simply use..
$registered_job = RegisteredJob::with('corporation', 'event')....

To recap ::

  1. Is belongsToMany still good for a table with more than 2 foreign keys?

  2. If not, should I refactor registered job table cuz my datbase schema has an issue in the first place?

Thanks

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

There is no problem or complication using three foreign keys in one model

BelongsToMany is only for use where the 'many' applies in both directions, ie a single event would need to belong to multiple corporations- i dont see that from your description

SangminKim's avatar

@SNAPEY - Thank you for the reply.

An event can have many registered jobs and one job can be registered for many events. The same for corporation. An event can have many corporations attending and one corporation can attend many events. Isn't it many-to-many relationship?

Please or to participate in this conversation.