2011-11-30 107 views
48

我可以在使用惰性加载的时候过滤掉Doctrine 2中arrayCollection的结果吗?例如,Doctrine 2 ArrayCollection过滤方法

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

目前还不清楚过滤方法是如何实际使用的。

+0

但仍然方法加载到许多数据,例如计数,加载所有匹配的数据。 – 2013-09-19 23:05:08

回答

66

的鲍里斯·伽利湖答案的这个职位,可以帮助你: Doctrine 2, query inside entities

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

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

使用过滤器方法的唯一问题是,您必须先取出所有数据,然后才能将其过滤出来,您知道是否有一种方法可以在不取出所有内容的情况下执行此操作? – Dennis

+0

嗨 - 我正在尝试以上,但得到语法错误,你能更新你的答案? – Sjwdavies

+0

@Sjwdavies我为你更新了它。 Missing()围绕$ idsToFilter。 – Jrgns

12

您的使用情况是:

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

如果添加 - >第(),你会得到只有返回的第一个条目,这不是你想要的。

@ Sjwdavies 您需要将()传递给USE的变量。您也可以缩短为in_array回报是一个布尔值已经:

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

Collection#filter方法确实渴望加载所有成员。 在SQL级别过滤将被添加在教条2.3中。

+1

现在2.3是真的吗?我没有在文档中找到它。 我们现在可以做类似过滤器和其他事情的东西,期望集合将过滤应用到查询并推迟查询吗? – Pinetree

+0

@Pinetree至少他们这样说:http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html#filtering-collections – Robin

101

原则现在有Criteria,它提供了一个API,用于根据上下文使用SQL和PHP过滤集合。

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

更新

这将实现结果的接受的答案,而不从数据库中获取的一切。

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); 
    } 
} 
+0

感谢您清除这将实际上改变sql查询,而不是选择数据库中的所有内容,然后通过循环应用过滤器! – tftd

+0

http:// stackoverflow。com/questions/35358597/in-predicate-with-criteria-filtering-isnt-working please,看看这里:) – DonCallisto

+0

在集合上使用'indexBy =“xxx”'并调用'匹配时出现一个问题'在上面,索引被丢弃。 https://github.com/doctrine/doctrine2/issues/4693 – fyrye