Reputation: 4650
I have 2 related entities - Category and Expense. Expense has a date - when the expense was made.
A Category entity has a one-to-many relationship with multiple Expense entities which themselves have a name(product) and a price property.
I want to calculate the sum of all expense->price properties for a single category for the current month. (I have working findExpensesForMonthAndCategory method)
Can you help me please?
Category
class Category
{
protected $name;
protected $expenses;
public function __construct()
{
$this->expenses = new ArrayCollection();
}
}
Expense
class Expense
{
protected $category;
protected $product;
protected $price;
protected $date;
}
Upvotes: 3
Views: 2210
Reputation: 52493
There are actually 2 ways of solving this.
Solution 1
Add a getExpenseSum() Method to your Category entity...
class Category
{
// ...
public function getExpenseSum()
{
$sum = 0;
foreach ($this->expenses as $expense) {
$sum += $expense->getPrice();
}
return $sum;
}
Now you can output the sum in twig this way:
{{ category.expenseSum }}
Solution 2
create a method in your repository.
// src/Vendor/YourBundle/Entity/ExpenseRepository
public function getSumByCategory($category)
{
$q = $this->createQueryBuilder('e')
->sum('e.price')
->where('e.category = :category')
->setParameter('category', $category)
->getQuery();
return $q->getResult();
}
Upvotes: 5