New to Doctrine. I'm trying to build a "list recent items function". It should get all records newer than 3 months but if the result is less than 50 records it should get older ones until 50 is fetched.
So if I have 100 records newer than three months I want to return all of them but nothing older. If I have 20 records from the last three months I want to return them and also the 30 most recent after that.
How would one do this with Doctrine? I don't want to make two queries (is it even called that?) if possible.
For now my EntityRepository just gets all records from the last three months as follows:
public function fetchRecent($from)
{
$criteria = new Criteria();
$criteria->where($criteria->expr()->gte('created', $from));
return $this->matching($criteria);
}
Edit
Hum, I read a bit too fast, you don't want to limit records if not older than three months. I don't see how to achieve this with a single query. (I'll think about it again but actually can't see..)
You could query the database to know how many recent records there are and then query the actual result.
public function fetchRecent($from, $nbRecords = 50)
{
$count = $this->createQueryBuilder('c')
->select('COUNT(c.id)')
->andWhere('c.created >= :from')->setParameter('from', $from)
->addOrderBy('c.created', 'desc');
$nbNewer = $count->getQuery()->getSingleScalarResult();
$query = $this->createQueryBuilder('q');
if ($nbNewer<$nbRecords) {
$query->setMaxResults($nbRecords);
} else {
$query->andWhere('q.created >= :from')->setParameter('from', $from);
}
$query->addOrderBy('q.created', 'desc');
return $query->getQuery()->getResult();
}