Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a findBy method with comparative criteria

I'd need to use a "magic finder" findBy method using comparative criteria (not only exact criteria). In other words, I need to do something like this:

$result = $purchases_repository->findBy(array("prize" => ">200")); 

so that I'd get all purchases where the prize is above 200.

like image 356
ElPiter Avatar asked Feb 09 '13 10:02

ElPiter


2 Answers

The class Doctrine\ORM\EntityRepository implements Doctrine\Common\Collections\Selectable API.

The Selectable interface is very flexible and quite new, but it will allow you to handle comparisons and more complex criteria easily on both repositories and single collections of items, regardless if in ORM or ODM or completely separate problems.

This would be a comparison criteria as you just requested as in Doctrine ORM 2.3.2:

$criteria = new \Doctrine\Common\Collections\Criteria(); $criteria->where(\Doctrine\Common\Collections\Criteria::expr()->gt('prize', 200));  $result = $entityRepository->matching($criteria); 

The major advantage in this API is that you are implementing some sort of strategy pattern here, and it works with repositories, collections, lazy collections and everywhere the Selectable API is implemented.

This allows you to get rid of dozens of special methods you wrote for your repositories (like findOneBySomethingWithParticularRule), and instead focus on writing your own criteria classes, each representing one of these particular filters.

like image 184
Ocramius Avatar answered Sep 23 '22 17:09

Ocramius


This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:

/**  * fetches Products that are more expansive than the given price  *   * @param int $price  * @return array  */ public function findProductsExpensiveThan($price) {   $em = $this->getEntityManager();   $qb = $em->createQueryBuilder();    $q  = $qb->select(array('p'))            ->from('YourProductBundle:Product', 'p')            ->where(              $qb->expr()->gt('p.price', $price)            )            ->orderBy('p.price', 'DESC')            ->getQuery();    return $q->getResult(); } 
like image 26
con Avatar answered Sep 24 '22 17:09

con