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

rovae's avatar
Level 1

3 tables many to many relationship how to code with eloquent

I have followings entities:

Task ( task_id - PK )

Company (company_id - PK)

User (user_id - PK)

Company-Task-User( id - PK, task_id - FK, company_id - FK, user_id - FK, status - boolean, end_date - Date )

how would i model the eloquent relationships?

0 likes
3 replies
GeordieJackson's avatar

I'd say you'd need to break it down.

How many companies can a user belong to?

Is a task assigned to 1 company or to many?

i.e. find the relationships between each of the entities individually and build the relationships from there.

rovae's avatar
Level 1

The relationship between company and task is from N to N, that has a pivot user_id ( Responsible for performing the task).

GeordieJackson's avatar

Many to many relationships are described here: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

So, Company belongsToMany Task, and Task belongsToMany Company.

Then do the same for Company - User and Task-User (depending on their specific relationships).

That way you'll build up all the necessary relations. You can then do all of the permutations in accessing models through their relations.

Please or to participate in this conversation.