Doctrine 2 ArrayCollection filter method

OrmDoctrine OrmLazy LoadingArraycollection

Orm Problem Overview


Can I filter out results from an arrayCollection in Doctrine 2 while using lazy loading? For example,

// users = ArrayCollection with User entities containing an "active" property
$customer->users->filter('active' => TRUE)->first()

It's unclear for me how the filter method is actually used.

Orm Solutions


Solution 1 - Orm

Doctrine now has Criteria which offers a single API for filtering collections with SQL and in PHP, depending on the context.

https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections

Update

This will achieve the result in the accepted answer, without getting everything from the database.

use Doctrine\Common\Collections\Criteria;

/**
 * @ORM\Entity
 */
class Member {
  // ...
  public function getCommentsFiltered($ids) {
    $criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));

    return $this->getComments()->matching($criteria); 
  }
}

Solution 2 - Orm

The Boris Guéry answer's at this post, may help you: https://stackoverflow.com/questions/7064528/doctrine-2-query-inside-entities

$idsToFilter = array(1,2,3,4);

$member->getComments()->filter(
    function($entry) use ($idsToFilter) {
       return in_array($entry->getId(), $idsToFilter);
    }
); 

Solution 3 - Orm

Your use case would be :

    $ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
                        return $user->getActive() === TRUE;
                    });
       

if you add ->first() you'll get only the first entry returned, which is not what you want.

@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:

    $member->getComments()->filter( function($entry) use ($idsToFilter) {
        return in_array($entry->getId(), $idsToFilter);
    });

Solution 4 - Orm

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDennisView Question on Stackoverflow
Solution 1 - OrmRyanView Answer on Stackoverflow
Solution 2 - OrmFredRogerView Answer on Stackoverflow
Solution 3 - OrmStéphan ChampagneView Answer on Stackoverflow
Solution 4 - OrmSmoky McPotView Answer on Stackoverflow