简体   繁体   中英

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 :)

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM