Laravel - Relationships - Has Many Through
The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform like Laravel Vapor. A Project
model might access many Deployment
models through an intermediate Environment
model. Using this example, you could easily gather all deployments for a given project. Let's look at the tables required to define this relationship:
projects
id - integer
name - string
environments
id - integer
project_id - integer
name - string
deployments
id - integer
environment_id - integer
commit_hash - string
Now that we have examined the table structure for the relationship, let's define the relationship on the Project
model:
hasManyThrough(Deployment::class, Environment::class);
}
}
The first argument passed to the hasManyThrough
method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.
Though the Deployment
model's table does not contain a project_id
column, the hasManyThrough
relation provides access to a project's deployments via $project->deployments
. To retrieve these models, Eloquent inspects the project_id
column on the intermediate Environment
model's table. After finding the relevant environment IDs, they are used to query the Deployment
model's table.