问题描述
我创建了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>
你能告诉我我做错了吗?
解决方法
我认为您需要颠倒:now和:lastMonth的顺序
->leftJoin('u.reports','r',Expr\Join::WITH,'r.createdAt BETWEEN :lastMonth AND :now')