我已经创建了symfony项目,并且有一个日期问题。我想提出一个在数据库中插入当前日期的请求。在我的实体中,我的字段是日期和时间。
存储库:
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $date_maj;控制器:
$qb = $this->getDoctrine()
->getManager()
->createQueryBuilder()
->update(Tache::class, 't')
->set('t.date_maj', date(('Y-m-d H:i:s'), time()))
->where('t.id = :id')
->setParameter('id', $id)
->getQuery()
->execute();错误:
[Syntax Error] line 0, col 87: Error: Expected end of string, got '06'发布于 2021-04-19 15:53:39
您希望设置一个值为PHP值的参数,类似于where子句中的:id。查询构建器将处理到数据库字符串值的转换:
$now = new \DateTime();
$qb = $this->getDoctrine()
->getManager()
->createQueryBuilder()
->update(Tache::class, 't')
->set('t.date_maj', ':now')
->where('t.id = :id')
->setParameter('now', $now)
->setParameter('id', $id)
->getQuery()
->execute();发布于 2021-04-19 17:49:01
您应该将实体与persist和flush一起使用,而不是使用queryBuilder。你的实体看起来像这样:
/**
* @ORM\Column(type="datetime", nullable=true)
* @var DateTime|null
*/
private $date_maj;
public function getDateMaj(): ?DateTime
{
return $this->date_maj;
}
public function setDateMaj(?DateTime $dateMaj): self
{
$this->date_maj = $dateMaj;
}和控制器端:
// it's for example, using injection dependency is better
$em = $this->getDoctrine()->getManager();
// Get your entity (if it's from Form, this line is useless, retrieve entity from $form->getData())
$tache = $em->getRepository(Tache::class)->find($id);
$now = new \DateTime();
$tache->setDateMaj($now);
$em->persist($tache);
$em->flush();如果没问题,你也可以把拼写错误的DateTime编辑成DateTimeInterface
发布于 2021-04-19 20:38:02
您可以使用new \DateTime()将其放入构造中
public function __construct()
{
$this->date_maj=new \DateTime();
}https://stackoverflow.com/questions/67157254
复制相似问题