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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14786937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:58:32  来源:igfitidea点击:

How to use a findBy method with comparative criteria

phpsymfonydoctrine-orm

提问by ElPiter

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:

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

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

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

这样我就可以买到奖品超过 200 的所有商品。

采纳答案by con

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:

这是一个使用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();
}

回答by Ocramius

The class Doctrine\ORM\EntityRepositoryimplements Doctrine\Common\Collections\SelectableAPI.

该类Doctrine\ORM\EntityRepository实现Doctrine\Common\Collections\SelectableAPI。

The Selectableinterface 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.

Selectable界面非常灵活且非常新,但它允许您在存储库和单个项目集合上轻松处理比较和更复杂的标准,无论是在 ORM 或 ODM 中还是完全独立的问题。

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

这将是您刚刚在 Doctrine ORM 中要求的比较标准2.3.2

$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($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 SelectableAPI is implemented.

这个 API 的主要优点是你在这里实现了某种策略模式,它适用于存储库、集合、惰性集合以及Selectable实现 API 的所有地方。

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.

这使您可以摆脱为存储库编写的数十种特殊方法(如findOneBySomethingWithParticularRule),而是专注于编写自己的标准类,每个类都代表这些特定过滤器之一。

回答by dbrumann

You have to use either DQLor the QueryBuilder. E.g. in your Purchase-EntityRepositoryyou could do something like this:

您必须使用DQLQueryBuilder。例如,在您的 Purchase- EntityRepository 中,您可以执行以下操作:

$q = $this->createQueryBuilder('p')
          ->where('p.prize > :purchasePrize')
          ->setParameter('purchasePrize', 200)
          ->getQuery();

$q->getResult();

For even more complex scenarios take a look at the Expr() class.

对于更复杂的场景,请查看Expr() 类

回答by Patrizio Onorati

$criteria = new \Doctrine\Common\Collections\Criteria();
    $criteria->where($criteria->expr()->gt('id', 'id'))
        ->setMaxResults(1)
        ->orderBy(array("id" => $criteria::DESC));

$results = $articlesRepo->matching($criteria);

回答by Jeff Clemens

The Symfony documentation now explicitly shows how to do this:

Symfony 文档现在明确地展示了如何做到这一点:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT p
    FROM AppBundle:Product p
    WHERE p.price > :price
    ORDER BY p.price ASC'
)->setParameter('price', '19.99');    
$products = $query->getResult();

From http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql

来自http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql

回答by Gander

I like to use such static methods:

我喜欢使用这样的静态方法:

$result = $purchases_repository->matching(
    Criteria::create()->where(
        Criteria::expr()->gt('prize', 200)
    )
);

Of course, you can push logic when it is 1 condition, but when you have more conditions it is better to divide it into fragments, configure and pass it to the method:

当然,条件为1的时候可以push逻辑,但是条件多的时候最好分片,配置后传给方法:

$expr = Criteria::expr();

$criteria = Criteria::create();
$criteria->where($expr->gt('prize', 200));
$criteria->orderBy(['prize' => Criteria::DESC]);

$result = $purchases_repository->matching($criteria);