【问题标题】:Doctrine 2 simple "bigger than" criteria教义 2 简单的“大于”标准
【发布时间】:2016-05-15 19:55:59
【问题描述】:

在 PDO / SQL 中,我有一个“大于”的简单查询:

DELETE * FROM tablexyz WHERE access > :old

Doctrine 2 ORM 中的等价物是什么?

我已经写了一点代码:

$criteria = ['access'=>$old];
$dataRepo = $entityManager->getRepository('tablexyz')->findBy($criteria)->delete();

我的问题是,我想在 Doctrine 2 ORM 中使用大于运算符,但我不想为此创建函数或类。有人知道更好或更短的解决方案吗?

【问题讨论】:

    标签: php pdo orm doctrine-orm doctrine


    【解决方案1】:

    您可以使用查询构建器,也可以直接对其执行 DQL(或 SQL)查询。

    $qb = $entityManager->createQueryBuilder();
    $qb->select('e')
       ->from('Entityxyz', 'e')
       ->where('e.access > :old')
       ->setParameter('old', $old);
    
    $entities = $qb->getQuery()->getResult();
    

    $query = 'SELECT e FROM AppBundle\Entity\Entityxyz WHERE e.access > :old';
    
    $entities = $entityManager->createQuery($query)
                              ->setParameter('old', $old)
                              ->getResult();`
    

    我建议你为它创建一个存储库方法,它是拥有它的正确位置。在存储库中使用查询构建器也更简单,因为它知道您正在引用哪个实体(并且可以跳过调用 select 和 from)

    class EntityxyzRepository extends EntityRepository
    {
        public function getNewerThan($newerThan)
        {
            $qb = $this->createQueryBuilder('e');
            $qb->where('e.access > :newerThan')
               ->setParameter('newerThan', $newerThan);
    
            return $qb->getQuery()->getResult();
        }
    }
    

    【讨论】:

    • 我想使用像“findBy”这样的教义功能。 Doctrine ORM / DBAL 中的 SQL 查询不是我想要的。
    • 你不能, findBy 只是为了非常简单的比较。对于更复杂的条件,您需要编写自己的方法
    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 2023-03-03
    • 2019-02-12
    • 2012-01-17
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多