我需要使用一个使用比较标准(不仅仅是精确标准)的“魔法查找器”findBy方法。换句话说,我需要这样做:
$result = $purchases_repository->findBy(array("prize" => ">200"));
这样我就能买到奖金超过200美元的所有商品。
发布于 2013-02-09 20:58:44
这是一个使用Expr() Class的例子-几天前我也需要这个,我花了一些时间来找出确切的语法和用法:
/**
* 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();
}
发布于 2013-02-10 00:20:15
Doctrine\ORM\EntityRepository
类实现了Doctrine\Common\Collections\Selectable
接口。
Selectable
接口非常灵活且非常新,但它将允许您轻松地处理存储库和单个项目集合上的比较和更复杂的标准,无论是在对象关系模型、对象模型或完全独立的问题中。
这将是您刚才在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);
这个应用程序接口的主要优点是,您在这里实现了某种策略模式,并且它可以与存储库、集合、惰性集合以及Selectable
应用程序接口实现的任何地方一起工作。
这使您可以摆脱为存储库(如findOneBySomethingWithParticularRule
)编写的几十个特殊方法,而是专注于编写自己的criteria类,每个类代表一个特定的过滤器。
发布于 2013-02-09 18:18:58
您必须使用DQL或QueryBuilder。例如,在你的Purchase-EntityRepository中,你可以这样做:
$q = $this->createQueryBuilder('p')
->where('p.prize > :purchasePrize')
->setParameter('purchasePrize', 200)
->getQuery();
$q->getResult();
对于更复杂的场景,请查看Expr() class。
https://stackoverflow.com/questions/14786937
复制相似问题