使用Doctrine DQL插入带有DateTime的mysql行

时间:2013-12-02 17:44:35

标签: php mysql datetime doctrine dql

我在尝试使用Doctrine DQL在我的MySQL表中插入一行时遇到了一些麻烦,具体来说,行正确插入但“创建”列显示了我桌上的00:00:00。

这是我的实体:

    class Packages
    {
        [... more irrelevant fields ...]
        /**
        * @var \DateTime
        * @ORM\Column(name="created", type="datetime", nullable=false)
        */
        private $created;
    }

这是我要插入的代码:

    $packages = new Packages;
    $packages->setCreated(new \DateTime("now"));
    [... more setters here ...]
    print_r($packages);  // See below for the print_r output
    $em = self::getEntityManager();        
    try{
        $em->persist($packages);
        $em->flush();
        return $packages->getPackageId();
    }catch(\Exception $e){
        $this->error = $e->getMessage();
        return false;
    }

在此处输出print_r,然后正确返回ID:

    Core\Entities\Packages Object
    (
        [..... More irrelevant fields set correctly .....]
        [created:Core\Entities\Packages:private] => DateTime Object        
        (
            [date] => 2013-12-02 09:37:18
            [timezone_type] => 3
            [timezone] => America/Los_Angeles
        )
    )

但后来发生了这件事

    mysql> select created from packages where package_id=1694;
    +---------------------+
    | created             |
    +---------------------+
    | 0000-00-00 00:00:00 |
    +---------------------+
    1 row in set (0.00 sec)

有没有人对此有任何线索?

1 个答案:

答案 0 :(得分:0)

尝试 1)在构造函数中创建的集合 要么 2)使用Lifecycle Callbacks prePersist