How to map MySQL column "timestamp" to a field with Doctrine2

20,668

Solution 1

You can just create a custom doctrine type defined timestamp, see the documentation

Solution 2

You can look at This post: datetime vs timestamp

Since it is a createdAt property, and represents a point in time, you might want to fetch objects that have been created before $createdAt or after $createdAt.

To do that, your best option is to store the datetime exactly the way you've done it but to associate a \Datetime object to that field: $this->createdAt = new \Datetime();


The best way for you would be to use lifecycle callbacks:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="biz_order")
 * @ORM\Entity(repositoryClass="Acme\OrderBundle\Repository\OrderRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Order
{
    /**
     * @ORM\Column(name="order_timestamp", type="datetime")
     */
    private $createdAt;    

    /**
     * @ORM\PrePersist
     */
    public function doStuffOnPrePersist()
    {
        $this->createdAt= new \DateTime();
    }


}
Share:
20,668
Tomas Dermisek
Author by

Tomas Dermisek

Updated on January 26, 2020

Comments

  • Tomas Dermisek
    Tomas Dermisek over 4 years

    I created a Doctrine2 Entity and would like to map a field to timestamp column in MySQL.

    /**
     * @ORM\Table(name="biz_order")
     * @ORM\Entity(repositoryClass="Acme\OrderBundle\Repository\OrderRepository")
     */
    class Order
    {
        /**
         * @ORM\Column(name="order_id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
    
        // Lots of other fields ...
    
        /**
         * @ORM\Column(name="order_timestamp", type="datetime")
         */
        private $createdOn;    
    }
    

    With annotated type as "datetime" I get following error:

    Doctrine\DBAL\Types\ConversionException: Could not convert database value "1390362851" to Doctrine Type datetime. Expected format: Y-m-d H:i:s

    at n/a in /var/www/packer/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/ConversionException.php line 63

    at Doctrine\DBAL\Types\ConversionException::conversionFailedFormat('1390362851', 'datetime', 'Y-m-d H:i:s') in /var/www/packer/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php line 67

    However in Doctrine 2.4 documentation I found following

    datetime: Type that maps a SQL DATETIME/TIMESTAMP to a PHP DateTime object.

    How can I map timestamp DB column to a PHP class field in Doctrine2?

    EDIT: So far my workaround is using the type="integer" in ORM mapping and returning it as ValueObject

    public function getCreatedOn()
    {
        $createdOn = new \DateTime();
        $createdOn->setTimestamp($this->createdOn);
        return $createdOn;
    }