我有这个YAML定义实体:原则2:保存“日期”字段
Entity\Visit:
type: entity
table: visit
fields:
date:
type: date
id: true
count:
type: integer
nullable: true
options:
unsigned: true
default: 1
lifecycleCallbacks: { }
和日期字段创建:
/**
* @var \DateTime
*
* @ORM\Column(name="date", type="date")
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $date;
如果我试图以这种方式插入新记录:
$date = new \DateTime('now');
$visit = new \Entity\Visit();
$visit->setDate($date);
$visit->setCount(1);
$em->persist($visit);
$em->flush();
我有这样的错误:
ContextErrorException in UnitOfWork.php line 1413: Catchable Fatal Error: Object of class DateTime could not be converted to string
而且我做了这种方式:显示
$date = new \DateTime('now');
$date = $date->format('Y-m-d');
此错误:
FatalThrowableError in DateType.php line 53: Call to a member function format() on string
任何人可以帮助我,以便插入(或更新)使用Doctrine2一个“日期”字段?谢谢。
UPDATE:数据库中的字段必须是'日期'字段。
您已经使用'@ORM \列(名称= “日期”,键入= “日期”) '并且您正在保存\ DateTime对象。所以首先改变'type = datetime'。 –
@ jigar-pancholi但我需要该字段是'日期'类型。 – cybtow
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html您可以将DateTime转换为prePersist上的字符串以进行插入/更新。 –