我想用Symfony和Doctrine找到我的腳,雖然我猜測它遠非優雅,但我設法得到了下面的工作IF我使用findall()
。我的主要問題是我試圖只返回尚未發生的事件。下面是一個使用expr()->gr()
我嘗試:將條件查詢應用於Doctrine的`getRepository()`
我的控制器:
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Form\Type\RegistrationType;
use AppBundle\Form\Model\Registration;
use AppBundle\Entity\Events;
use Doctrine\ORM\EntityRepository;
class DefaultController extends Controller
{
/**
* @Route("/events", name="events")
*/
public function eventsAction(Request $request)
{
$calendar = $this->getDoctrine()
->getRepository('AppBundle:Events');
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('EventDate',date('Y-m-d H:i:s')));
$list=$calendar->matching($criteria);
return $this->render('default/events.html.twig', array(
'title' => 'Events',
'list' => $list,
));
}
}
我Events.php
實體是:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Events
*
* @ORM\Table(name="Events")
* @ORM\Entity
*/
class Events
{
/**
* @var \DateTime
*
* @ORM\Column(name="EventDate", type="date", nullable=false)
*/
private $eventdate;
當我嘗試加載網頁,我得到:
Unrecognized field: EventDate
我假設這是一個區分大小寫的問題?我在我的數據庫(EventDate
)和我的Events
實體註釋指定name="EventDate"
。我試圖改變private $eventdate
到private $EventDate
,但是這給了我一個更加嚴肅的錯誤,所以我趕緊退到:
FatalErrorException in DateType.php line 53: Error: Call to a member function format() on a non-object
使用DateTime代替日期:'new \ DateTime('now')'而不是'date('Ymd H:i:s')' – Matteo
謝謝@Matteo - 我一定會記得, - ) – Bendy