I'm using Symfony2 and Doctrine.
I have a date field, here it is:
/**
* @ORM\Column(type="date")
*/
protected $date;
In my form I use a text field to avoid Chrome default datepicker, but I insert DateTime objects in the database:
if ($request->isMethod('POST')) {
$form->bind($request);
//Convert string date to DateTime object and send it to database as object
$dateObj = \DateTime::createfromformat('d-m-Y', $expense->getDate());
$expense->setDate($dateObj);
// ...
and then I want to find all items with a specific date:
public function findExpensesForDate($user, $date)
{
$q = $this
->createQueryBuilder('e')
->where('e.date = :date')
->andWhere('e.user = :user')
->setParameter('date', $date)
->setParameter('user', $user)
->getQuery();
return $q->getResult();
}
and call it like this:
$expenses_for_today = $this->repository->findExpensesForDate($this->user, $today);
which returns nothing when
$today = new /DateTime();
and returns the results when
$today_obj = new /DateTime();
$today = $today_obj->format('Y-m-d');
So why when I give the date as object this doesn't work? Isn't the reason to use date filed is to take advantage of quering with DateTime objects? I guess I'm missing something trivial and important, but I just can't see what, or I'm not understanding the situation quite well. My understanding is like this: the field is of type date, so I should insert DateTime objects in it and when quering I should also you DateTime objects. Can you please help me to fix this?
P.S.: I tried changing the field to datetime:
/**
* @ORM\Column(type="datetime")
*/
protected $date;
but there was no change.
And at all is it OK and good to query with string? Will I get the advantage of using objects when querying that way?