2016-08-23 53 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

相关问题