2011-09-01 32 views
8

我有以下查询:如何限制Doctrine2中的关联实体结果?

$query = $this->getEntityManager()->createQuery(' 
         SELECT u, p, m 
         FROM MyCoreBundle:User u 
         JOIN u.programmes p 
         JOIN u.motivation m 
         '); 

$result = $query->getResult(); 

我要限制的动机返回的对象为每个用户是哪些,我在其他地方使用(在激励库)本次查询的结果:

$query = $this->getEntityManager()->createQuery(' 
         SELECT m FROM MyCoreBundle:Motivation m 
         WHERE m.user = :user 
         ORDER BY m.date DESC'); 

$query->setParameter('user',$user); 
$query->setFirstResult(0); 
$query->setMaxResults(1); 
//@TODO if there is not result recorded for the user, return sth which indicates this 
return $query->getResult(); 

有没有办法在第一个查询或更好的方法中限制和限制动机?

+1

考虑写在下面,并假设“最新motiviation”是最重要的对你,这将是访问了很多,可能的解决方案是创建'User:LatestMotivation' OneToOne relatinship。然后每次添加一个新的Motivation实体时,(通过Doctrine'prePersist'事件)用新添加的一个更新'LatestMotivation'。通过这种方式,您将能够遍历许多获取最新动机的“用户”记录。 HTH –

回答

14

您不能限制关节行的数量。

如果你有学说2.1,你可以在集合使用->slice()

$collection = $user->getMotivations(); // returns a LazyCollection, 
              // makes no SQL query 

$motivations = $collection->slice(0, 20); // queries the first 20 motivations 
              // for this user (if the association 
              // was not fetch-joint) 

http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/extra-lazy-associations.html

+0

谢谢 - 我通过向我的用户实体添加另一种方法来增加一个单一的动机条目,循环播放对象并覆盖$动机属性。脏,但它的作品。 – codecowboy

+2

@ amaud576875不幸的是,slice方法仅为当前用户初始化关联。如果循环多个用户,则会生成多个查询。有没有办法如何为所有用户获取切片集合? –

+1

@PetrPeller我有类似的问题。你有没有设法解决它? – svlada

相关问题