Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 ArrayCollection filter method

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.

like image 434
Dennis Avatar asked Nov 30 '11 23:11

Dennis


2 Answers

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);    } } 
like image 92
Ryan Avatar answered Oct 12 '22 04:10

Ryan


The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities

$idsToFilter = array(1,2,3,4);  $member->getComments()->filter(     function($entry) use ($idsToFilter) {        return in_array($entry->getId(), $idsToFilter);     } );  
like image 26
FredRoger Avatar answered Oct 12 '22 05:10

FredRoger