【问题标题】:ORM removes duplicates. But not everywhereORM 删除重复项。但并非无处不在
【发布时间】:2021-09-15 10:23:09
【问题描述】:

我正在通过存储库 (ORM) 进行一些数据库查询,我想获取对象列表。

我的问题是什么? 我在存储库中有两种方法:getList() 获取列表,getCount() 获取信息的总记录数。 getList() 给我 5 条记录,getCount() 给我数字 9。

    public function getList($criteria, $page, $limit, $orderBy, $joins = [])
    {
        $qb = $this->createQueryBuilder('a')->select('a');
        if(!empty($joins)) {
            $qb = $this->setCriteriaByJoins($qb, $joins);
        }
        $qb = $this->setCriteriaToQuery($qb, $criteria);

        foreach($orderBy as $order) {
            $qb->addOrderBy('a.' . $order[0], $order[1]);
        }
        if($page && $limit) {
            $offset = ($page - 1) * $limit;
            $qb->setFirstResult($offset)
                ->setMaxResults($limit);
        }

        $result = $qb->getQuery()->getResult();

        return $result;
    }
    public function getCount($criteria = [], $joins = []) {
        try {
            $qb = $this->createQueryBuilder('a')->select('count(a.id)');
            if(!empty($joins)) {
                $qb = $this->setCriteriaByJoins($qb, $joins);
            }
            $qb = $this->setCriteriaToQuery($qb, $criteria);
            $result = $qb->getQuery()->getSingleScalarResult();
        } catch(\Exception $e) {
            $result = 0;
        }
        return $result;
    }

在调试中,我看到getList() 请求是这样构建的:

SELECT r0 _. * FROM film r0_ LEFT JOIN person_film r1_ ON (r0_.id = r1_.film_id) WHERE r1_.person_id IN (45793) AND r0_.status = 1 ORDER BY r0_.`release` DESC, r0_.id DESC LIMIT 48

getCount()

SELECT count (r0_.id) AS sclr_0 FROM film r0_ LEFT JOIN person_film r1_ ON (r0_.id = r1_.film_id) WHERE r1_.person_id IN (45793) AND r0_.status = 1

从存储库中请求 getList() 会给我 5 条记录。但是,如果我直接用这个查询(没有 ORM)询问数据库,那么我会得到 9 条记录。在这 9 条记录中,有 4 条是重复的,因为person_film 表可以包含多个具有相同film_idperson_id 的记录(这些记录在其他字段中有所不同)。我发现/vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:hydrateRowData() 删除了重复项。

  1. 如何使getList()请求中的ORM返回所有9条记录,即使它们是重复的?

  2. 反之亦然。怎么办到getCount()返回5.

【问题讨论】:

    标签: php doctrine-orm doctrine


    【解决方案1】:

    看来这是第二个问题的答案

        public function getCount($criteria = [], $joins = [], $distinct = false) {
            try {
                $sq = ($distinct) ? 'count(distinct(a.id))' : 'count(a.id)';
                $qb = $this->createQueryBuilder('a')->select($sq);
                if(!empty($joins)) {
                    $qb = $this->setCriteriaByJoins($qb, $joins);
                }
                $qb = $this->setCriteriaToQuery($qb, $criteria);
                $result = $qb->getQuery()->getSingleScalarResult();
            } catch(\Exception $e) {
                $result = 0;
            }
            return $result;
        }
    

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 2021-06-06
      • 2016-07-26
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      相关资源
      最近更新 更多