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

alex_hill's avatar

Sum related values with a filter on multiple tables

I have three models:

  1. FinancialPeriod
  2. FinancialValue
  3. CostCentre

A CostCentre is in a Many-to-Many relationship FinancialPeriod with the pivot table being the FinancialValue table. Essentially a Cost Centre will have multiple FinancialValues for a FinancialPeriod (planned revenue, actual revenue etc).

I have also set up two BelongsTo relationships from the FinancialValue to CostCentre and FinancialPeriod tables (and their respective HasMany relationships)

I am able to show the actual revenue of a single CostCentre for a filtered set of FinancialPeriod (the Financial Year) using code similar to:

$cc = \App\CostCentre::firstorFail();
$actual = $cc->financial_periods()
                    ->wherePivot('type','=','Actual')
                    ->whereFinancialYear('FY16')
                    ->orderBy('month')
                    ->get();

What I would like to be able to do is show a combined view of actual revenue for a financial year. i.e. Show me the sum of all FinancialValues (by FinancialPeriod) that are tagged as 'Actual' which belong to a FinancialPeriod with a FinancialYear of 'FY16'. This is where I am having trouble structuring my eloquent query (trying to filter on two different tables, and to sum at a per FinancialPeriod basis).

The output would ideally be a collection of FinancialPeriods with the Sum of the FinancialValue across all CostCentres that I can then use to output a table by period.

Any assistance would be appreciated.

0 likes
2 replies
bobbybouwmann's avatar

If you find it really hard to create a query, just make the query in plain mysql and then convert it to Eloquent. I think you are better of with some joins here instead of using relations. I guess you can us Eloquent relations, but then we need some more information on how your tables look like and what the relations are between them

alex_hill's avatar

It's funny - I work with SQL every day (in another job) and one of the things I struggled with when starting to learn Laravel was Object Oriented queries and Eloquent. I forced myself to not write raw SQL and learn the "eloquent way", but I think you are right, this is probably a case where an SQL query would be a better option.

Please or to participate in this conversation.