spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

ON UPDATE CURRENT_TIMESTAMP #265

Closed dertin closed 6 years ago

dertin commented 6 years ago

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.

FlipEverything commented 6 years ago

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]
    ];
  }
FlipEverything commented 6 years ago

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