You can use the Criteria API to filter the collection:
<?php
use Doctrine\Common\Collections\Criteria;
class Article
{
/**
* @ORM\OneToMany(targetEntity="Comment", mappedBy="article")
*/
protected $comments;
public function getComments($showPending = false)
{
$criteria = Criteria::create();
if ($showPending !== true) {
$criteria->where(Criteria::expr()->eq('approved', true));
}
return $this->comments->matching($criteria);
}
}
This is especially nice, because Doctrine is smart enough to only go to the database if the collection hasn’t already been loaded.