如何使用 Doctrine 对连接表求和

Fae*_*ery 3 symfony doctrine-orm twig

我有 2 个相关实体 - 类别和费用。费用有一个日期 - 费用发生的时间。

类别实体与多个费用实体具有一对多关系,这些实体本身具有名称(产品)和价格属性。

我想计算当月单个类别的所有费用-> 价格属性的总和。(我有工作 findExpensesForMonthAndCategory 方法)

你能帮我吗?

类别

class Category
{
    protected $name;
    protected $expenses;

    public function __construct()
    {
        $this->expenses = new ArrayCollection();
    }
}
Run Code Online (Sandbox Code Playgroud)

费用

class Expense
{
    protected $category;
    protected $product;
    protected $price;
    protected $date;
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ich 5

实际上有两种方法可以解决这个问题。

解决方案1

将 getExpenseSum() 方法添加到您的 Category 实体...

class Category 
{

// ...

    public function getExpenseSum() 
    {    
        $sum = 0;
        foreach ($this->expenses as $expense) {
            $sum += $expense->getPrice();
        }

        return $sum;
     }
Run Code Online (Sandbox Code Playgroud)

现在你可以用这种方式在树枝中输出总和:

     {{ category.expenseSum }}
Run Code Online (Sandbox Code Playgroud)

解决方案2

在您的存储库中创建一个方法。

// 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();
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法自动让 Doctrine 对实体进行查询?Doctrine 知道关系和数据类型 - 因此在新属性上使用某种注释来做到这一点会很棒。 (2认同)