Sum of associated Fields

I have a problem with 2 Tables, i need a sum of associated table

Table 1 projects:

id title
1 Project A
2 Project B

Table 2 jobs:

id project_id hours
1 1 3
2 1 2
3 1 1
4 2 4

Association in ProjectsTable:

Expected output:
Project A : 6 hours
Project B : 4 hours

Can anyone help me? I tried a lot but it wont work.

Please share an example or two of what you tried, and how they failed. It’s often easier to fix something that’s close than to create it from scratch for you.

I tried something like this in many variations…

$qry = $this->find();
‘hours’ => $query->func()->SUM(‘Jobs.hours’)

the result after $qry->all(), toArray, toList ist often Jobs.hours does not exist. i also tried to add contain.

Is this what you’re looking for?


$queryJobs = TableRegistry::getTableLocator()->get('Jobs')->find();
$jobsByProject = $queryJobs
			'title' => 'Projects.title',
			'hours' => $queryJobs->func()->sum('Jobs.hours'),



    "title": "Project A",
    "hours": 6
    "title": "Project B",
    "hours": 4

Thanks Brent. Thats exactly what i am looking for. You made my day!