2016-08-23 56 views
0

我有這個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:數據庫中的字段必須是'日期'字段。

+0

您已經使用'@ORM \列(名稱= 「日期」,鍵入= 「日期」) '並且您正在保存\ DateTime對象。所以首先改變'type = datetime'。 –

+0

@ jigar-pancholi但我需要該字段是'日期'類型。 – cybtow

+0

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html您可以將DateTime轉換爲prePersist上的字符串以進行插入/更新。 –

回答

0

最後,我通過自己發現了問題:這個問題是因爲主鍵是日期列。看來,學說不喜歡那些東西。

我的新YML文件:

Entity\Visit: 
    type: entity 
    table: visit 
    fields: 
     id: 
      type: integer 
      id: true 
      generator: 
       strategy: AUTO 
      options: 
       unsigned: true 
     date: 
      type: date 
      unique: true 
     count: 
      type: integer 
      nullable: true 
      options: 
       unsigned: true 
       default: 1 

    lifecycleCallbacks: { } 

現在,我可以這樣做:

$date = new \DateTime('now'); 
$visit = new \Entity\Visit(); 
$visit->setDate($date); 
$visit->setCount(1); 
$em->persist($visit); 
$em->flush(); 
0

請下面的代碼嘗試:

$date = new \DateTime(); 

$visit = new \Entity\Visit(); 
$visit->setDate($date->format('Y-m-d')); 
$visit->setCount(1); 
$em->persist($visit); 
$em->flush(); 
+0

謝謝,但正如我在queestion中寫的,如果我這樣做,那麼會顯示此錯誤:** DateType.php中的FatalThrowableError第53行:調用成員函數格式()字符串** – cybtow

相關問題