DuckHunter's avatar

HasManyThrough Relationships

Looking for some help with this one. In the example of HasManyThrough in the laravel documentation, it shows an example of the following tables. You can define a HasManyThrough relationship to obtain deployments in relation to projects through the intermediate table of environments.

projects
    id - integer
    name - string
 
environments
    id - integer
    project_id - integer
    name - string
 
deployments
    id - integer
    environment_id - integer
    commit_hash - string

In my use case, however, my relationships are as follows:

projects
    id - integer
    name - string
 
environments
    id - integer
    project_id - integer
    deployment_id - integer
    name - string
 
deployments
    id - integer
    commit_hash - string

I have different names for my tables, so in this case the table names don't really make sense, but essentially a project can have multiple environments and a deployment can have multiple environments. The environments belong to both a project and a deployment.

I want to be able to find all deployments that are related to projects via the environments table. Ideally, there could be multiple references to the same deployment but it would only return a list of deployments without the duplicates.

I tried using projects HasManyThrough(deployments, environments) but that returned an error indicating that I did not have an environment_id in deployments, which is anticipated but not what I am looking for.

Any ideas here?

0 likes
4 replies
LaryAI's avatar
Level 58

Well, it looks like you've got yourself in a bit of a pickle! It's a good thing you asked the experts here at Laracasts for help.

The solution is to use a custom query to get the data you need. You can use the join method to join the projects, environments, and deployments tables together, and then use the select method to get the data you need. Here's an example of what the query might look like:

$deployments = DB::table('projects')
    ->join('environments', 'projects.id', '=', 'environments.project_id')
    ->join('deployments', 'environments.deployment_id', '=', 'deployments.id')
    ->select('deployments.*')
    ->get();

And there you have it! Now you can get all the deployments related to projects through the environments table.

Good luck!

Related Series/Forum Thread: https://laracasts.com/discuss/channels/eloquent/hasmanythrough-relationships

DuckHunter's avatar

Is there a way to do this through eloquent relationships?

ddoddsr's avatar

I am working on the same kind of schema difference, where the through (your environments) table has both keys just like your example. Is this like a pivot table? Have you tried anything in that direction?

Please or to participate in this conversation.