我有這個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上的字符串以進行插入/更新。 –