手动更新gedmo timestamptable

时间:2014-08-16 09:11:14

标签: php symfony doctrine-orm

所以我使用的是学说扩展here,它基本上生成了一个基于时间戳的创建。我现在尝试通过执行以下操作来覆盖设置时间戳:

public function setTimestampDecay()
    {
         $this->created->sub(new \DateInterval('PT4M'));
         return $this;
    }

所以我想从这个实体中的createdTimestamp中减去4分钟,所以这就是我所做的:

 $em = $this->getDoctrine()->getManager();
        $picture = $em->getRepository('AppMainBundle:ShopPicture')->findOneById(821478);
        $picture->setTimestampDecay();
        $em->flush();

现在当我在设置时间戳衰减后打印picture->getCreated()时,它会显示正确的时间。但问题是它不会持久存储到数据库中。当我检查数据库时,它实际上是与之前相同的时间戳,我将其设置为衰减。为什么是这样?是否可以手动修改学说扩展名上的时间戳?

2 个答案:

答案 0 :(得分:1)

为什么要在创建对象之前将创建时间戳设置为4分钟?这似乎有点误导我。

无论如何,请忘记使用Gedmo Timestampable设置创建日期。只需在对象的构造函数中设置时间戳,因为只有在创建对象时才会调用构造函数。

Gedmo的prestersable行为是在prePersist上触发的,因此很有可能会覆盖您手动设置的时间戳,这就是您遇到此问题的原因。

答案 1 :(得分:0)

我也遇到过类似的情况。就我而言,最初我将默认值存储在一个时区中,我们希望将其更改为 UTC +0:00。

使用实体管理器进行此类更新的问题是,它会被侦听器覆盖。

解决方案是使用 PDO,我是这样做的。

use Doctrine\DBAL\Driver\Connection;

// Inject this as a service in your controller
$connection = new Connection();

$items = $connection->fetchAll('SELECT id, created, updated FROM table_name');
foreach ($items as $item) {
    $created = \DateTime::createFromFormat('Y-m-d H:i:s', $item['created'])->modify('-3 hours');
    $updated = \DateTime::createFromFormat('Y-m-d H:i:s', $item['updated'])->modify('-3 hours');
    $sql = 'UPDATE table_name SET created = :created, updated = :updated WHERE item.id = :item_id';
    $statement = $connection->prepare($sql);
    $statement->bindValue(":created", $created->format('Y-m-d H:i:s'));
    $statement->bindValue(":updated", $updated->format('Y-m-d H:i:s'));
    $statement->bindValue(":item_id", $item['id']);
    $statement->execute();
}