原则HasLifecycleCallbacks PrePersist | PreUpdate不会触发 [英] Doctrine HasLifecycleCallbacks PrePersist|PreUpdate don't fire
问题描述
我正在将教义2与ZF2和教义模块一起使用。
我编写了一个需要PreUpdate | PrePersist的实体,因为Doctrine不允许在主键中使用
Date | Datetime:
I'm using Doctrine 2 with ZF2 and the Doctrine-Module. I've written an Entity that needs a PreUpdate|PrePersist, because Doctrine doesn't allow Date|Datetime in a primary key:
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="sample")
*/
class Sample
{
/**
*
* @ORM\Id
* @ORM\Column(type="string")
* @var integer
*/
protected $runmode;
/**
*
* @ORM\Id
* @ORM\Column(type="date")
* @var DateTime
*/
protected $date;
public function getRunmode()
{
return $this->runmode;
}
public function setRunmode($runmode)
{
$this->runmode = $runmode;
return $this;
}
public function getDate()
{
return $this->date;
}
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
*
* @ORM\PreUpdate
* @ORM\PrePersist
*/
protected function formatDate()
{
die('preUpdate, prePersist');
if ($this->date instanceof \DateTime) {
$this->date = $this->date->format('Y-m-d');
}
return $this;
}
}
现在的问题是,如果我将DateTime设置为Date我收到消息:
The Problem is now, if i set a DateTime as a Date I get the message:
"Object of class DateTime could not be converted to string"
因为它没有进入formatDate。
because it doesn't walk into the formatDate.
推荐答案
首先,由于您将字段 Sample#date
映射为 datetime
,则应始终为 null
或 DateTime
的实例。
First of all, since you mapped the field Sample#date
as datetime
, it should always be either null
or an instance of DateTime
.
因此,您应该键入 setDate
方法,如下所示:
Therefore, you should typehint your setDate
method as following:
public function setDate(\DateTime $date = null)
{
$this->date = $date;
return $this;
}
此外,您的的可见性,未调用project.org/projects/doctrine-orm/zh-CN/latest/reference/events.html#lifecycle-events rel = noreferrer>生命周期回调 formatDate 受保护,因此ORM无法访问。将其更改为
public
即可使用。无论如何,都无需进行任何转换,因此您可以摆脱它。
Also, your lifecycle callback is not invoked because the visibility of method formatDate
is protected
, therefore not accessible by the ORM. Change it into public
and it will work. No conversion should be necessary anyway, so you can get rid of it.
这篇关于原则HasLifecycleCallbacks PrePersist | PreUpdate不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!