试图理解 Doctrine Criteria() 以及是否可以缓存

Trying to understand Doctrine Criteria() and if caching is possible

我需要写一个简单的查询:SELECT propertyName from TABLE_NAME WHERE abc > 10

我相信我不能用简单的 $repository->findBy() 来做到这一点,所以相信 DQL(或查询构建器)可以完成这项工作。像这样:

$query = $this->createQueryBuilder('x')
      ->where('x.abc > :amt')
      ->setParameter('amt', 10)
      ->getQuery();

$query->getResult();

但是,我听说 Doctrine "Criteria" 可以从 Doctrine 2.3 获得,是一种更好的方法。

(1) 我看的文档很少,但 DQL 的推广最多。有人可以给我一个非常简单的代码示例,它与我上面的代码示例相同(但使用 Criteria)吗?

(2)缓存呢?我知道我可以用 DQL 做到这一点,但是 Criteria 呢?

$query->useResultCache('cache_id');

From the docs:

The Criteria has a limited matching language that works both on the SQL and on the PHP collection level. This means you can use collection matching interchangeably, independent of in-memory or sql-backed collections.

另一个有趣的答案可以是: How to use a findBy method with comparative criteria

顺便说一句,我认为缓存仅依赖于查询对象本身和 Doctrine 层,因此 Criteria 仅用于编写自定义选择或匹配机制。

因此您可以将查询以最优雅的形式编写为:

    $qb = $this->createQueryBuilder('x'); 
    $query = $qb
        ->where($qb->expr()->gt("x.abc",":amt"))
        ->setParameter('amt', 10)
        ->getQuery();

希望对您有所帮助

我直接用在集合关系中查询

仅举个例子,这就是我使用 Doctrine Criteria 的方式:

class User implements AdvancedUserInterface
{

  ....

    /**
     * One-To-Many
     *
     * @ORM\OneToMany(targetEntity="Acme\ADemoBundle\Entity\Transaction", mappedBy="user")
     * @ORM\OrderBy({"position" = "ASC"})
     */
    protected $transactions;

    public function getLastTransaction()
    {
        $criteria = Criteria::create()
                        ->orderBy(array('eventAt'=>'DESC'))
                        ->setFirstResult(0)
                        ->setMaxResults(1);

        return $this->transactions->matching($criteria)->first();
    }
 }