简体   繁体   English

通过Symfony中的条件查询相关实体(学说)

[英]Querying for related entities by condition in Symfony(doctrine)

For this question you need to know about 2 entities : 对于这个问题,您需要了解2个实体:
Loan and Charge. 贷款和抵押。 One Loan has Multiple Charges. 一笔贷款有多项费用。
So, in my controller, I am querying for each entity and it seems to be lame. 因此,在我的控制器中,我正在查询每个实体,这似乎很la脚。

$query = $this->getDoctrine()
    ->getRepository('AppBundle:Loan')
    ->find($id);

$query1 = $em->createQuery(
'SELECT p
FROM AppBundle:Charge p
WHERE p.loanId = :loanId
AND p.isActive = true
')->setParameter('loanId', $id);

I want to transform query1 in smth better, using relationship. 我想使用关系更好地转换query1。
So, from my point of view it must be smth like : 因此,从我的角度来看,它一定像:

    foreach($query->getCharges() as $charge) {
     if($charge->getIsActive() == true) {
      //what to put here?
     }
  }

If condition passes, how can I obtain the same object that came from DB from my first code? 如果条件通过,如何从我的第一个代码中获得与DB相同的对象?

You can create an extra method on your Loan class that uses ArrayCollections::filter : 您可以在使用ArrayCollections::filter Loan类上创建一个额外的方法:

public function getActiveCharges()
{
    return $this->getCharges()->filter(function (Charge $charge) {
        return $charge->getIsActive() === true;

        //or you can omit '=== true'
        return $charge->getIsActive();
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM