In your scenario, you're trying to use hasManyThrough to access users through a pivot table, which isn't directly supported by hasManyThrough. The hasManyThrough and hasOneThrough relationships are designed for traversing through a single intermediary model, not through a pivot table. For pivot tables, you should use belongsToMany.
Here's how you can set up the relationships correctly:
-
User Model: To get all sites through projects owned by the user, your existing
hasManyThroughrelationship is correct.public function sites(): HasManyThrough { return $this->hasManyThrough(Site::class, Project::class); } -
Site Model: To get the owner of the site, your
hasOneThroughrelationship is also correct, assuming the keys are set up properly.public function owner(): HasOneThrough { return $this->hasOneThrough( User::class, Project::class, 'id', // Foreign key on the projects table... 'id', // Foreign key on the users table... 'project_id', // Local key on the sites table... 'user_id' // Local key on the projects table... ); } -
Site Model: To get all users associated with a project through the
project_userpivot table, you should usebelongsToMany.public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'project_user', 'project_id', 'user_id'); }However, since the
project_usertable is related to projects, you should define this relationship on theProjectmodel instead:// In Project Model public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'project_user', 'project_id', 'user_id'); }Then, you can access the users from a site like this:
// In Site Model public function projectUsers(): BelongsToMany { return $this->project->users(); }Ensure that you have a
projectrelationship defined in theSitemodel:public function project(): BelongsTo { return $this->belongsTo(Project::class); }
By using belongsToMany for pivot tables, you can correctly access all users associated with a project. If you need to access these users directly from the Site model, you can create a custom method or use the project relationship to access the users.