Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 : custom orderBy clause

I would like to fetch some events, ordered and paginated by those criteria :

  • opened events in less than 20km
  • incoming events in less than 20km
  • opened events further than 20km
  • incoming events further than 20km

I can deal with the opened/incoming order, but I'm not able to cut the < 20km first, here's what my query builder look like :

public function fetchByLocation($day, $time, $latitude, $longitude, $page = 1, $itemPerPage = 10)
{
    if(!$page) {
        $page = 1;
    }

    $qb = $this->createQueryBuilder('event')
        ->select('event', 'GEO_DISTANCE(:latitude, :longitude, event.latitude, event.longitude) AS distance')
        ->setParameter('latitude', $latitude)
        ->setParameter('longitude', $longitude)
        ->where('(event.day = :day AND event.start >= :time) OR event.day > :day')
        ->setParameter('day', $day)
        ->setParameter('time', $time)
        ->addOrderBy('event.day', 'asc')
        ->addOrderBy('event.start', 'asc');


    $qb->setFirstResult(($page - 1) * $itemPerPage)
        ->setMaxResults($itemPerPage);

    return $qb->getQuery()->getResult();
}

This would provide the events with opened first, any idea to handle the < 20km criterion in the query builder ? Do I have to use native query ? Can I mix both ?

Many thanks for considering my request :)

like image 789
Thomas Piard Avatar asked Dec 01 '14 11:12

Thomas Piard


1 Answers

what you want is to distinguish between events that are "close" and "far". you should add

->addSelect('(CASE WHEN distance > 20 then 1 ELSE 0 END) AS is_far')
->addOrderBy('is_far ASC')
like image 115
Bartłomiej Wach Avatar answered Oct 29 '22 16:10

Bartłomiej Wach