How can I limit an associated entity result in Doctrine2?
I have the following query:
$query = $this->getEntityManager()->createQuery('
SELECT u, p, m
FROM MyCoreBundle:User u
JOIN u.programmes p
JOIN u.motivation m
');
$result = $query->getResult();
I want to restrict the motivation objects returned for each user to be the result of this second query which I am using elsewhere (On the Motivation repository):
$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->getRe开发者_运维知识库sult();
Is there a way to limit and restrict motivation in the first query or a better approach?
You can't limit the number of joint rows.
If you have Doctrine 2.1 you can use ->slice()
on the collection:
$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)
See http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/extra-lazy-associations.html
精彩评论