'Laravel eloquent query with multiple child relations
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
Solution 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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |