我正在使用Doctrine 2和ZF2以及Doctrine-Module.我写了一个需要PreUpdate | PrePersist的实体,因为Doctrine不允许在主键中使用Date | Datetime:
<?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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是现在,如果我将DateTime设置为日期,我会收到消息:
"Object of class DateTime could not be converted to string"
Run Code Online (Sandbox Code Playgroud)
因为它不会走进formatDate.
首先,由于您将字段映射Sample#date为datetime,因此它应该始终是null或者是实例DateTime.
因此,您应该setDate按以下方式键入您的方法:
public function setDate(\DateTime $date = null)
{
$this->date = $date;
return $this;
}
Run Code Online (Sandbox Code Playgroud)
此外,您的生命周期回调,则不会调用,因为方法的可视性formatDate是protected,因此不被ORM访问.改变它public,它会工作.无论如何都不需要转换,所以你可以摆脱它.
| 归档时间: |
|
| 查看次数: |
7589 次 |
| 最近记录: |