Symfony2 datetime best way to store timestamps?

后端 未结 4 719
醉话见心
醉话见心 2020-12-15 08:55

I don\'t know which is the best way to store a timestamp in the database. I want to store the entire date with hours minutes and seconds but it only stores the date ( for in

4条回答
  •  甜味超标
    2020-12-15 09:42

    The best way to store a timestamp in the database is obviously to use the timestamp column if your database supports that type. And since you can set that column to autoupdate on create, you dont even have to provide a setter for it.

    There is a Timestampable behavior extension for Doctrine 2 which does exactly that from the userland side as well:

    Timestampable behavior will automate the update of date fields on your Entities or Documents. It works through annotations and can update fields on creation, update or even on specific property value change.

    Features:

    • Automatic predifined date field update on creation, update and even on record property changes
    • ORM and ODM support using same listener
    • Specific annotations for properties, and no interface required
    • Can react to specific property or relation changes to specific value
    • Can be nested with other behaviors
    • Annotation, Yaml and Xml mapping support for extensions

    With this behavior, all you need to do is change your annotation to

    /**
     * @var datetime $created
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    private $created;
    

    Then you dont need to call setCreated in your code. The field will be set automatically when the Entity is created for the first time.

提交回复
热议问题