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

Qlic's avatar
Level 18

How do i access a pivot with a pivot through my models

I have three tables that need to work together.

  • users
  • projects
  • vehicles

a project can have many vehicles. a vehicle can have many projects. a vehicle can have many users. a user can have many vehicles.

I have the following models:

  • User
  • Project (belongsToMany Vehicle)
  • Vehicle (belongsToMany Project)
  • VehicleUser (belongsToMany Project & hasManyThrough User, Vehicle)

The hasManyThrough does not seem to work due to the fact that the id's are not like the laravel docs example.

My table structure is illustrated in the following image: http://i63.tinypic.com/mvrqt5.png However i can't figure out how to retrieve the users bound to each vehicle bound to a project.

How do you guys go about doing this?

  • Edit: Basically this query is what i would need in Eloquent markup.
SELECT
    D.*,
    E.*
FROM
    `project_vehicle` A
INNER JOIN
    `projects` B
ON
    A.project_id = B.id
INNER JOIN
    `project_vehicle_user` C
ON
    A.id = C.project_vehicle_id
INNER JOIN
    `users` D
ON
    C.user_id = D.id
INNER JOIN
    `vehicles` E
ON
    A.vehicle_id = E.id
WHERE
    A.project_id = 1
0 likes
0 replies

Please or to participate in this conversation.