如何使用具有比较条件的 findBy 方法
2022-08-30 08:01:24
我需要使用“魔术查找器”findBy方法,使用比较标准(不仅仅是精确标准)。换句话说,我需要做这样的事情:
$result = $purchases_repository->findBy(array("prize" => ">200"));
这样我就可以获得奖品超过200的所有购买。
我需要使用“魔术查找器”findBy方法,使用比较标准(不仅仅是精确标准)。换句话说,我需要做这样的事情:
$result = $purchases_repository->findBy(array("prize" => ">200"));
这样我就可以获得奖品超过200的所有购买。
类 Doctrine\ORM\EntityRepository
实现了 Doctrine\Common\Collections\Selectable
API。
该界面非常灵活且非常新,但它将允许您在存储库和单个项目集合上轻松处理比较和更复杂的条件,无论是在ORM还是ODM中还是完全独立的问题。Selectable
这将是您刚刚要求的比较标准,如教义ORM中所示:2.3.2
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where(\Doctrine\Common\Collections\Criteria::expr()->gt('prize', 200));
$result = $entityRepository->matching($criteria);
此 API 的主要优点是,您在此处实现了某种策略模式,并且它适用于存储库、集合、惰性集合以及实现 API 的任何地方。Selectable
这使您可以摆脱为存储库编写的数十种特殊方法(如 ),而是专注于编写自己的标准类,每个类代表这些特定过滤器之一。findOneBySomethingWithParticularRule
这是一个使用Expr()类的示例 - 几天前我也需要这个,我花了一些时间来找出确切的语法和使用方式:
/**
* 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();
}