3
votes

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;
}
2
Did you created field manually in the database?Vail
I am building an application that is sharing DB with a legacy application and so I have to map existing DB structure to the new Entities.Tomas Dermisek

2 Answers

2
votes

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

1
votes

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();
    }


}