原则 2 - 通过存储库使用限制时获取总数
Doctrine 2 - Get total when using limit via repository
我是 Doctrine 的新手,当我对 Criteria
使用 limit 时(通过 setMaxResults
函数)在 EntityRepository::matching
方法中。
在我的存储库(不是 EntityRepository 的 extend
)中,我使用以下代码(我知道这不是最佳代码,它仅用于学习 Doctrine):
public function getAll($query = null) {
if ($query instanceof Criteria) {
$users = $this->em->getRepository('App\Entities\User')->matching($query)->toArray();
} else {
$users = $this->em->getRepository('App\Entities\User')->findAll();
}
return $users;
}
现在假设条件定义如下:
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
$query->setMaxResults(10);
实际上有超过 10 个用户匹配。
如何获取符合条件的用户总数?
如果将 maxResults
设置为 10,则会得到 10 个结果 ;)。
为什么不调用 getAll()
获取所有结果并稍后应用 MaxResults
?
//search for Ron's
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
//check how many Ron's your database can find
$count = $repo->getAll($query)->count();
//get the first 10 records
$query->setMaxResults(10);
$users = $repo->getAll($query);
我是 Doctrine 的新手,当我对 Criteria
使用 limit 时(通过 setMaxResults
函数)在 EntityRepository::matching
方法中。
在我的存储库(不是 EntityRepository 的 extend
)中,我使用以下代码(我知道这不是最佳代码,它仅用于学习 Doctrine):
public function getAll($query = null) {
if ($query instanceof Criteria) {
$users = $this->em->getRepository('App\Entities\User')->matching($query)->toArray();
} else {
$users = $this->em->getRepository('App\Entities\User')->findAll();
}
return $users;
}
现在假设条件定义如下:
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
$query->setMaxResults(10);
实际上有超过 10 个用户匹配。
如何获取符合条件的用户总数?
如果将 maxResults
设置为 10,则会得到 10 个结果 ;)。
为什么不调用 getAll()
获取所有结果并稍后应用 MaxResults
?
//search for Ron's
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
//check how many Ron's your database can find
$count = $repo->getAll($query)->count();
//get the first 10 records
$query->setMaxResults(10);
$users = $repo->getAll($query);