created
列
记录是第一次创建。我找到了这个示例,但它适用于onUpdate
样式,因此每次更新记录时都会更新updated
列。
/**
* @var datetime $updated
*
* @ORM\Column(type="datetime")
*/
protected $updated;
/**
* @ORM\PrePersist
*/
public function setUpdatedPrePersist()
{
$this->updated = date('Y-m-d H:i:s');
}
答案 0 :(得分:3)
简单可靠的解决方案是在作曲家中要求以下扩展名: https://github.com/stof/StofDoctrineExtensionsBundle/blob/master/Resources/doc/index.rst
然后只需添加以下内容即可更新您的实体:
<?php
// src/YourCompany/YourBundle/Entity/Demo.php
namespace YourCompany\YourBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Demo
{
// ....
/**
* @var datetime $created
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
private $created;
/**
* @var datetime $updated
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
private $updated;
}
就是这样! :)
注意:确保在配置中启用timestampable侦听器,即:
stof_doctrine_extensions:
orm:
default:
timestampable: true
如果你不喜欢站在巨人的肩膀上:
<?php
// src/YourCompany/YourBundle/Entity/Demo.php
namespace YourCompany\YourBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Demo
{
// ...
/**
* @var datetime $created
*
* @ORM\Column(type="datetime")
*/
protected $created;
/**
* @var datetime $updated
*
* @ORM\Column(type="datetime")
*/
protected $updated;
/**
* @ORM\PrePersist
*/
public function onPrePersist()
{
$this->created = new \DateTime();
$this->updated = new \DateTime();
}
/**
* @ORM\PreUpdate
*/
public function onPreUpdate()
{
$this->updated = new \DateTime();
}
// ...
}