hasManyThrough() use first "through" relationship only

Viewed 187

I am currently struggling with the hasManyThrough() function. Basically, I'm trying to eager load an n to n relationship, but I only want to include the first "through" relationship. Here's an example:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    /**
     * Get all of the deployments for the project.
     */
    public function deployments()
    {
        return $this->hasManyThrough(Deployment::class, Environment::class);
    }
project:
   id: 1
   name: Project1

environment:
   id: 1
   project_id: 1
   name: environment1

   id: 2
   project_id: 1
   name: environment2

deployment:
   id: 1
   environment_id: 1
   commit_hash: xxxx1

   id: 2
   environment_id: 1
   commit_hash: xxx11

   id: 3
   environment_id: 2
   commit_hash: xxxx2

The deployments() function here obviously returns all the deployments for all environments of a specific project. How would I be able to only fetch the deployments of the first (or last) environments entry of a projects entry? In this case, this would be the environment with id: 1 and deployments with id: 1 and id: 2, for example.

1 Answers

I think you may want to specify a hasOne relationship like so:

// Project.php
public function environment()
{
    return $this->hasOne(Environment::class);
}

And then you could eager-load the deployments using:

Project::with(['environment.deployments'])

I don't think you will be able to build a developments() relationship function on Project but someone might prove me wrong.

Related