如何限制Doctrine2中的关联实体结果?

时间:2011-09-01 10:53:23

标签: php doctrine-orm symfony

我有以下查询:

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

$result = $query->getResult();

我想限制为每个用户返回的动机对象是我在其他地方使用的第二个查询的结果(在Motivation存储库中):

$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 个答案:

答案 0 :(得分:14)

您无法限制关节行数。

如果你有Doctrine 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