我怎样才能对这个学说查询返回的实体对象数组进行排序?

时间:2015-11-17 12:58:36

标签: symfony doctrine-orm dql

对于以下路线,我想返回当前日期或之后的事件列表 - 但是我遇到了问题,因为我只知道如何做到:< / p>

  1. 返回按日期排序的所有对象
  2. 在'今天'之后归还所有对象
  3. ......但我无法弄清楚如何一起做两件事。

    以下是我目前的代码:

    控制器

    namespace AppBundle\Controller;
    
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;
    use AppBundle\Entity\Events;
    
    
    class DefaultController extends Controller
    {
        /**
        * @Route("/events", name="events")
        */
        public function eventsAction(Request $request)
        {
          $calendar = $this->getDoctrine()->getRepository('AppBundle:Events')->findAll();
    
          $criteria = new \Doctrine\Common\Collections\Criteria();
          $criteria->where($criteria->expr()->gt('eventdate',new \DateTime('now') ));
    
          $list=$calendar->matching($criteria);
    
          if (!$calendar) {
                throw $this->createNotFoundException('No event found for ID ',$list);
          }
    
          return $this->render('default/events.html.twig', array(
                'title' => 'Events',
                 'list' => $list,
                 'message' => '',
          ));
        }
    }
    

    实体存储库

    namespace AppBundle\Entity\Repository;
    
    use Doctrine\ORM\EntityRepository;
    
    class EventRepository extends EntityRepository
    {
        public function findAll()
        {
            return $this->findBy(array(), array('eventdate' => 'ASC'));
        }
    }
    

    事件实体

    namespace AppBundle\Entity;
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * Events
     *
     * @ORM\Table(name="Events")
     * @ORM\Entity
     * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\EventRepository")
     */
    class Events
    {
        /**
         * @var \DateTime
         *
         * @ORM\Column(name="EventDate", type="date", nullable=false)
         */
        private $eventdate;
    
         /* .... */
    }
    

1 个答案:

答案 0 :(得分:2)

//在您的存储库中

public function getAllFutureEvents()
{
     return $this->getEntityManager()->createQuery(
        'SELECT b FROM AppBundle:Event e
        WHERE e.eventdate > CURRENT_DATE()
        ORDER BY e.eventdate DESC'
    )->getResult();
}

//在控制器内:

$events = $this->getDoctrine()->getRepository('AppBundle:Events')->getAllFutureEvents();