Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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->getResult();

Is there a way to limit and restrict motivation in the first query or a better approach?

like image 378
codecowboy Avatar asked Sep 01 '11 10:09

codecowboy


1 Answers

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

like image 148
Arnaud Le Blanc Avatar answered Oct 19 '22 04:10

Arnaud Le Blanc