Reputation: 155
For this question you need to know about 2 entities :
Loan and Charge. One Loan has Multiple Charges.
So, in my controller, I am querying for each entity and it seems to be lame.
$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.
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?
Upvotes: 0
Views: 1676
Reputation: 10144
You can create an extra method on your Loan
class that uses ArrayCollections::filter
:
public function getActiveCharges()
{
return $this->getCharges()->filter(function (Charge $charge) {
return $charge->getIsActive() === true;
//or you can omit '=== true'
return $charge->getIsActive();
});
}
Upvotes: 1