我正在使用 Symfony2 和 Doctrine。
我有一个日期字段,在这里:
/**
* @ORM\Column(type="date")
*/
protected $date;
在我的表单中,我使用文本字段来避免 Chrome 默认日期选择器,但我在数据库中插入 DateTime 对象:
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);
// ...
然后我想查找具有特定日期的所有项目:
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();
}
并这样调用它:
$expenses_for_today = $this->repository->findExpensesForDate($this->user, $today);
什么都不返回
$today = new /DateTime();
并返回结果时
$today_obj = new /DateTime();
$today = $today_obj->format('Y-m-d');
那么为什么当我将日期作为对象时这不起作用?使用日期归档的原因不是为了利用 DateTime 对象的查询吗?我想我错过了一些琐碎而重要的事情,但我只是看不到什么,或者我不太了解情况。我的理解是这样的:该字段是日期类型的,所以我应该在其中插入 DateTime 对象,并且在查询时我也应该插入 DateTime 对象。你能帮我解决这个问题吗?
P.S.:我尝试将字段更改为日期时间:
/**
* @ORM\Column(type="datetime")
*/
protected $date;
但是没有任何变化。
用字符串查询真的好吗?以这种方式查询时,我会得到使用对象的优势吗?
最佳答案
我认为这是因为 DateTime 对象太具体了,还有小时、分钟和秒,所以它不能等于数据库中的注册日期!
如果要使用DateTime对象,需要获取一天的开始日期和结束日期才能得到当天的所有结果!您必须比较日期间隔以获取其间的所有日期。
首先,获取当天的开始和结束日期(为简化起见,我们将结束日期设为第二天的开始,并将其排除在请求中):
$fromDate = new \DateTime('now'); // Have for example 2013-06-10 09:53:21
$fromDate->setTime(0, 0, 0); // Modify to 2013-06-10 00:00:00, beginning of the day
$toDate = clone $fromDate;
$toDate->modify('+1 day'); // Have 2013-06-11 00:00:00
并修改你的方法:
public function findExpensesForDate($user, $fromDate, $toDate)
{
$q = $this
->createQueryBuilder('e')
->where('e.date >= :fromDate')
->andWhere('e.date < :toDate')
->andWhere('e.user = :user')
->setParameter('fromDate', $fromDate)
->setParameter('toDate', $toDate)
->setParameter('user', $user)
->getQuery();
return $q->getResult();
}
就是这样,它应该可以工作,这里是脚本:
$expenses_for_today = $this->repository->findExpensesForDate($this->user, $fromDate, $toDate);
因此您将获得 2013-06-10 00:00:00 和 2013-06-11 00:00:00 之间的所有日期(不包括), 所以当天的结果!
关于date - Doctrine 的日期字段——query 的写法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17018055/