如何使用具有比较标准的 findBy 方法

2022-01-03 00:00:00 php doctrine-orm

我需要使用使用比较标准(不仅是精确标准)的魔术查找器" findBy 方法.换句话说,我需要做这样的事情:

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"));

这样我就可以购买所有奖励超过 200 的商品.

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

推荐答案

这是一个使用 Expr() Class - 几天前我也需要这个,我花了一些时间才知道确切的语法是什么及使用方式:

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

相关文章