Doctrine 2 ArrayCollection Filter Method

Can I filter results from an array in Doctrine 2 when using lazy loading? For example,

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

It is unclear how the filter method is used.

+48
orm doctrine2 lazy-loading arraycollection
Nov 30 '11 at 23:11
source share
4 answers

Boris Gehry's answer on this post may help you: Doctrine 2, request inside objects

 $idsToFilter = array(1,2,3,4); $member->getComments()->filter( function($entry) use ($idsToFilter) { return in_array($entry->getId(), $idsToFilter); } ); 
+66
Dec 01 '11 at 5:21
source share

Doctrine now has Criteria , which offers one API for filtering collections with SQL and PHP, depending on context.

http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html#filtering-collections

Update

This will produce 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); } } 
+100
Sep 03 '13 at 4:22
source share

Your use case:

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

if you add β†’ first (), you will only get the first entry entered, which is not what you want.

@Sjwdavies You need to put () around the variable you pass to the USE. You can also shorten since in_array already returns a boolean:

  $member->getComments()->filter( function($entry) use ($idsToFilter) { return in_array($entry->getId(), $idsToFilter); }); 
+11
May 10 '12 at 14:22
source share

The Collection#filter method really loads all members. SQL-level filtering will be added to Doctrine 2.3.

-one
Aug 30 '12 at 12:24
source share



All Articles