Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

carincon93's avatar

Two counts with multiple inner join

I have 3 tables with relationships

Projects ProjectEvaluations => project_id Observations => project_id

I need to generate two counts, one for qty of project evaluations and other one for observations

Like this

How can I do?

-----------.------------
count 1 |  count 2 |
    10           3
------------------------
0 likes
4 replies
carincon93's avatar

@staudenmeir yes

// Project
public function EvaluationProject()
{
        return $this->hasMany('App\EvaluationProject');
}

public function Observation()
{
        return $this->hasOne('App\Observation');
}
// EvaluationProject
public function Project()
{
        return $this->belongsTo('App\Project');
}
// Observation
public function Project()
{
        return $this->belongsTo('App\Observation');
}
staudenmeir's avatar
Level 24

You can use withCount():

$projects = Project::withCount('evaluations', 'observations')->get();
foreach($projects as $project) {
    // $project->evaluations_count
    // $project->observations_count
}

Please or to participate in this conversation.