Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony entity setmaxresult/limit on array collection

Is it possible to set a max amount of result when retrieving related objects in a one-to-many relationship using the "lazy load"?

Example:
Lets say a Person have shoes

$person = $em->find($id);
$person->getShoes();

This will fetch everything from the shoes table with person_id. But what if I only want to show the last 5 shoes that where added to the db?

Or is the only solution use the Paginator and do:

$em->createQuery('...')->setMaxResult(5);
like image 329
Christopher Hoyos Avatar asked Jul 27 '15 17:07

Christopher Hoyos


1 Answers

You can use doctrine's Criteria class to filter/sort/limit your records

public function getShoes() {
    $criteria = \Doctrine\Common\Collections\Criteria::create()
        ->orderBy(array('your_property_to_sort_collection'=> \Doctrine\Common\Collections\Criteria::DESC))
        ->setMaxResults(5);
    return $this->shoes->matching($criteria);
}
like image 130
M Khalid Junaid Avatar answered Sep 21 '22 19:09

M Khalid Junaid