0

I am working on a query but can't find the solution to this one.

The structure i have at the moment is:

A project has 1 machine, but a machine can belong to multiple projects. A machine can have multiple issues.

Now i want to get all projects with the issues created after the project got created.

The query that i have at the moment, but doesn't work:

        $allProjects = Project::with(['machine',
        'machine.issues' => function ($query) {
                $query->where('created_at', '>=', 'project.created_at');
            }
        ])
        ->orderBy('id')
        ->get();

I am not getting the issues at all by using this query, when i switch the operator to: < then i get all the issues even the ones after project.created_at

1
  • Can you provide the laravel version you are running? Commented Feb 7, 2022 at 11:49

1 Answer 1

1

You can have a pivot do most of the work for you. I tried reproducing your problem statement as below.

 <?php

 class Project extends Model
 {
    use HasFactory;

    public function machine()
    {
       return $this->hasOneThrough(Machine::class, MachineProject::class, 'machine_id', 'id', 'id', 'project_id');
    }

    public function issues()
    {
       return $this->hasManyThrough(Issue::class, Machine::class, 'id', 'machine_id')->whereDate('issues.created_at', '<=', $this->created_at);
    }
}


class Machine extends Model
{
    use HasFactory;

    public $with = ['issues'];

    public function projects()
    {
        return $this->belongsToMany(Project::class);
    }

    public function issues()
    {
        return $this->hasMany(Issue::class);
    }
}


class Issue extends Model
{
    use HasFactory;

    public function machine()
    {
        return $this->belongsTo(Machine::class);
    }
}


class MachineProject extends Pivot
{
    //
}

To retrieve the Project with issues, you just do

$allProjects = Project::with(['machine' => function ($machine) {
    $machine->with('issues');
}])->get();
Sign up to request clarification or add additional context in comments.

2 Comments

At the moment i can get the projects with all the machine issues, but i only need to get issues with created_at >= project->created_at
@LesleyPeters You can achieve this on the model easily. I updated the answer. Check the issues method on the Project model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.