我想编写一个 DQL 查询来选择发布并加入另一个实体。
这是我的代码:
$dql = '
SELECT p , h ,t ,m
FROM App:Post p
LEFT JOIN p.mentions m
LEFT JOIN p.tags t
LEFT JOIN p.file h
WHERE p.user
IN (
SELECT f FROM App:User u
JOIN u.followers f
WHERE u.id = :uid
)
OR p.user = :uid ';
$query = $this->getEntityManager()
->createQuery($dql)
->setMaxResults(5)
->setParameters(['uid' => $user->getId()])
->getArrayResult();
但问题是 setMaxResults
不限制帖子实体而是限制标签实体在 5 上。
这是我的两种结果:
1.with setMaxResults (Not work fine)
2.with setMaxResults (Work fine)
我的代码有什么问题?
最佳答案
这是在没有分页器的情况下使用 setMaxResults() 或 setFirstResult() 时原则中的预期行为。
setMaxResults() 实际上是在生成的查询中添加一个SQL LIMIT,它不仅会像您期望的那样限制根实体,还会限制查询返回的行.这意味着在连接查询时它不会执行您想要的操作。
If your query contains a fetch-joined collection specifying the result limit methods are not working as you would expect. Set Max Results restricts the number of database result rows, however in the case of fetch-joined collections one root entity might appear in many rows, effectively hydrating less than the specified number of results.
你可以做些什么来实现你想要的是使用 Paginator关于您的查询:
$query = $this->getEntityManager()
->createQuery($dql)
->setMaxResults(5)
->setParameters(['uid' => $user->getId()]);
$paginator = new Paginator($query, $fetchJoinCollection = true);
$c = count($paginator);
foreach ($paginator as $post) {
}
来自上面的 Paginator 文档链接:
Paginating Doctrine queries is not as simple as you might think in the beginning. If you have complex fetch-join scenarios with one-to-many or many-to-many associations using the "default" LIMIT functionality of database vendors is not sufficient to get the correct results.
另外,请注意:
By default the pagination extension does the following steps to compute the correct result:
- 使用
DISTINCT
关键字执行计数查询。 - 使用
DISTINCT
执行限制子查询以查找当前页面中的实体的所有 ID。 - 执行 WHERE IN 查询以获取当前页面的所有结果。
This behavior is only necessary if you actually fetch join a to-many collection. You can disable this behavior by setting the $fetchJoinCollection flag to false; in that case only 2 instead of the 3 queries described are executed. We hope to automate the detection for this in the future.
关于php - 当 Doctrine 查询加入时,setMaxResults 不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50199102/