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
Sum related values with a filter on multiple tables
I have three models:
- FinancialPeriod
- FinancialValue
- 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.
Please or to participate in this conversation.