spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer

Home Page:http://phpdatamapper.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ON UPDATE CURRENT_TIMESTAMP

dertin opened this issue · comments

How to define a field that is updated with the date of last modification?
ON UPDATE CURRENT_TIMESTAMP

I am integrating the library (Spot ORM) in my php framework.

Thank you.

This is not something you can do out-of-the-box with the current implementation of spot. I used a simple workaround to achieve this functionality. You can do something like this:

Define a custom type:

<?php
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class OnUpdateCurrentTimestamp extends Type
{
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return $value;
    }
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return $value;
    }
    public function getName()
    {
        return 'onupdatecurrenttimestamp';
    }
    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return 'timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP';
    }
}

You have to register the custom type:

\Doctrine\DBAL\Types\Type::addType('onupdatecurrenttimestamp', 'OnUpdateCurrentTimestamp');

After that you can use this custom type inside the entity definition:

public static function fields()
  {
    return [
      'modified' => ['type' => 'onupdatecurrenttimestamp', 'notnull' => true]
    ];
  }

Feel free to reopen this thread if you need further assistance.