【问题标题】:Doctrine: Count left joined with condition rows学说:计数左连接条件行
【发布时间】:2020-08-23 13:53:28
【问题描述】:

我创建了 symfony 5 项目,其中包含带有报告的用户实体(OneToMany 关系)。我使用 knp 分页器创建了包含用户数据的表。现在我想增加按上个月报告数量排序用户数据的可能性(在我使用标准获取此数字之前,但用户数据无法按此数字排序)。因此,我将 leftJoin 报告添加到用户数据并在查询中进行计数。一切正常,但是当我在上个月添加限制加入报告时('r.createdAt BETWEEN :now AND :lastMonth) 结果对于所有用户始终为 '0'。

通过用户仓库获取用户数据的代码:

    public function findAllQuery(string $searchTerms): Query
    {   

        if ($searchTerms) {
            return $this->searchByTermsQuery($searchTerms);
        }

        return $this->createQueryBuilder('u')
            /* This join counts reports correctly but it counts all reports by user (without date limitation)
            ->leftJoin('u.reports', 'r')
            */
            ->leftJoin('u.reports', 'r', Expr\Join::WITH, 'r.createdAt BETWEEN :now AND :lastMonth')
            ->addSelect('COUNT(r.id) AS monthReports')
            ->setParameters([
                'now' => new \DateTime('now'),
                'lastMonth' => new \Datetime('last month')
            ])
            ->groupBy('u.id')
            ->getQuery()
        ;
    }

及分页码:

    <th {% if pagination.isSorted('monthReports') %} class="sorted" {% endif %}>
        {{ knp_pagination_sortable(pagination, 'Month reports', 'monthReports') }}
    </th>
//....
    <td>
        {{ user.monthReports }}
    </td>

你能告诉我我做错了什么吗?

【问题讨论】:

    标签: symfony collections doctrine


    【解决方案1】:

    我认为你需要颠倒 :now 和 :lastMonth 的顺序

     ->leftJoin('u.reports', 'r', Expr\Join::WITH, 'r.createdAt BETWEEN :lastMonth AND :now')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 2016-03-14
      • 1970-01-01
      • 2015-07-18
      • 2015-05-13
      • 1970-01-01
      相关资源
      最近更新 更多