Search code examples
symfonydoctrine-ormdql

How could I sort the array of entity objects returned by this doctrine query?


For the below route I want to return a list of Events that are on or after the current date - however I'm having problems as I'm only aware of how to do either:

  1. Return all objects sorted by date
  2. Return all objects after 'today'

...but I can't work out how to do both together.

Below is my current code:

Controller

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' => '',
      ));
    }
}

Entity repository

namespace AppBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

class EventRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('eventdate' => 'ASC'));
    }
}

Events entity

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;

     /* .... */
}

Solution

  • // inside your repository

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

    // inside your controller:

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