我假设您只需要这个字段,而不需要您的AdminGoals
实体。在你的AdminGoalsRepository
你可以这样做:
public function getGoalsByUser(User $user)
{
$qb = $this->createQueryBuilder('goal');
$qb->select('SUM(savings.value) AS savings_value')
->addSelect('goal.created')
->addSelect('goal.description')
->addSelect('goal.goalDate')
->addSelect('goal.value')
->addSelect('goal.budgetCat') //is this an entity? it will be just an ID
->join('goal.adminSavings', 'savings', Join::WITH))
->where($qb->expr()->eq('goal.user', ':user'))
->groupBy('goal.id')
->setParameter('user', $user);
return $qb->getQuery()->getScalarResult();
}
请记住,返回对象将是一个行数组,每行都是一个关联的数组,其键与上面的映射类似。
Edit
更新问题后,我将更改我建议的功能,但如果其他人想看到差异,我将保留上面的示例。
首先,因为这是一个单向的 ManyToOneAdminSavings
and AdminGoals
,自定义查询应该位于AdminSavingsRepository
(不像上面那样)。另外,既然你想要一个聚合字段 http://doctrine-orm.readthedocs.org/en/latest/cookbook/aggregate-fields.html这会"break"您的一些数据获取。当您不仅仅是渲染模板时,请尝试保持尽可能多的 OOP。
public function getSavingsByUser(User $user)
{
$qb = $this->createQueryBuilder('savings');
//now we can use the expr() function
$qb->select('SUM(savings.value) AS savings_value')
->addSelect('goal.created')
->addSelect('goal.description')
->addSelect('goal.goalDate')
->addSelect('goal.value')
->addSelect('goal.budgetCat') //this will be just an ID
->join('savings.goal', 'goal', Join::WITH))
->where($qb->expr()->eq('goal.user', ':user'))
->groupBy('goal.id')
->setParameter('user', $user);
return $qb->getQuery()->getScalarResult();
}
Bonus
public function FooAction($args)
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
//check if user is User etc depends on your config
...
$savings = $em->getRepository('AcmeBundle:AdminSavings')->getSavingsByUser($user);
foreach($savings as $row) {
$savings = $row['savings_value'];
$goalId = $row['id'];
$goalCreated = $row['created'];
[...]
}
[...]
}