Home Ask Login Register

Developers Planet

Your answer is one click away!

barbieswimcrew February 2016

How to get doctrine2 entity one to many entities that are set "active"

Let's assume there is a OneToMany doctrine2 association between blogposts and comments. A blogposts might have many comments. Every comment remains inactive and therefore hidden in the frontend until a moderator will activate the comment manually.

I'm now trying to have some kind of security facade to ensure that only "active" comments will be provided to the view by accessing them in a loop over the {{blogpost.comments}} variable in the twig template.

Trying to use the getComments() method in the blogpost entity I was trying to filter the ArrayCollection of comments like so

 * @return ArrayCollection
public function getComments()
    return $this->comments->filter(function ($condition) {
        return $condition->getActive() === true;

unfortunately Doctrine will entirely load every single comment even if the relations fetch mode is set to "EXTRA_LAZY". So that would influence the performance of an application in a way i'd like to avoid.

Is there any way to hide the inactive comments globally or do I have to take care of filtering them every time I'm accessing the blogpost.comments relations in the view?


Raphaël Malié February 2016

You should use the matching method of your collection. If your collection is not loaded, it will add filters to the SQL query to only load what you need. If your collection is already loaded, it will filter the PHP array.

use Doctrine\Common\Collections\Criteria;

public function getComments()
    return $this->comments->matching(
            Criteria::expr()->eq('active', true)

More informations here: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections


Post Status

Asked in February 2016
Viewed 1,524 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life