带有额外汇总字段的学说实体储存库。

问题描述 投票:0回答:1

我有一个实体 Client,与一个实体的关系 Contract. 合同有了领域 amount 和外地 payingDelay.

Client.php

/**
 * @ORM\OneToMany(targetEntity="Contract", mappedBy="client")
 * @ORM\JoinColumn(name="contract_id", referencedColumnName="id")
 */
private $contract;

我想显示一个所有客户的列表,其中有一些基本的客户字段,也有一些合同的计算信息(SUM等),像这样。

name - num contracts    - sum(amounts)  - aggregated risk
John - COUNT(contracts) - SUM(C.amount) - SUM(C.amount * C.payingDelay) 

This is my basic `findClientWithCalculations()` method in `ClientRepository`:

        return $this->createQueryBuilder('CLI')
            ->join('CLI.contract', 'CON')
            ->orderBy('CON.startDate', 'DESC')
            ->getQuery()
            ->getResult();

Is there a way I can add extra columns to this QueryBuilder, even if the final structure doesn't match the structure of a Client object or this must be done outside from a repository?

If not, maybe I can build a custom query in a controller and pass the query result to a twig template to show this structure.

Thank you.

doctrine repository entity
1个回答
0
投票

虽然不是小事,但问题的表述并不正确。我认为一个实体库方法必须实现某种类型的 findBy() 方法,并返回这个存储库所属的那个实体的一个对象或对象集合。

其实一个实体仓库方法可以返回任何东西,所以这个问题可以在实体仓库方法里面使用本地查询来解决。

比如说

ClientRepository.php:

public function findWithContractStatus($contractStatusShortname)
{
    $em = $this->getEntityManager();

    $clientQuery = "select distinct CLI.id, CLI.name, COUNT(contracts) as ncontracts, SUM(C.amount) as amount from client CLI join contract CON on CON.client_id = CON.id group by CLI.id, CLI.name"

    $rsm = new ResultSetMapping();
    $rsm->addScalarResult('id', 'id');
    $rsm->addScalarResult('name', 'name');
    $rsm->addScalarResult('ncontracts', 'ncontracts');
    $rsm->addScalarResult('amount', 'amount');

    $query = $em->createNativeQuery($clientQuery, $rsm);
    return $query->getResult();
}

这将会返回一个给定结构的数组 -- id, name, ncontracts, amount(金额) - 可以在控制器、树枝模板或任何地方进行迭代。

© www.soinside.com 2019 - 2024. All rights reserved.