我是Symfony2(或Symfony3)的新手,我找不到如何设置doctrine(带注释配置),以便在“创建”或“修改”字段时自动将其保存在我的实体中。
答案 0 :(得分:38)
此后我的解决方案......
您只需将其直接放入您的实体类中:
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class MyEntity {
//....
public function __construct() {
// we set up "created"+"modified"
$this->setCreated(new \DateTime());
if ($this->getModified() == null) {
$this->setModified(new \DateTime());
}
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function updateModifiedDatetime() {
// update the modified time
$this->setModified(new \DateTime());
}
//....
}
实际上效果很好
答案 1 :(得分:24)
您可以使用StofDoctrineExtensionsBundle。这在symfony cookbook中描述。它包含Timestampable行为。
/**
* @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;
答案 2 :(得分:9)
/**
*
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function updatedTimestamps()
{
$this->setModifiedAt(new \DateTime(date('Y-m-d H:i:s')));
if($this->getCreatedAt() == null)
{
$this->setCreatedAt(new \DateTime(date('Y-m-d H:i:s')));
}
}
您无需拨打__constructor
任何内容。只需创建getter
和setter
属性created
,modified
即可。
如果您在每次更新时首先设置setCreated()
,您还会更新created
列。所以先放setModifedAt()
答案 3 :(得分:5)
另外两个示例(如果您使用的是Yaml或Xml映射):
Entity\Product:
type: entity
table: products
id:
id:
type: integer
generator:
strategy: AUTO
fields:
name:
type: string
length: 32
created_at:
type: date
gedmo:
timestampable:
on: create
updated_at:
type: datetime
gedmo:
timestampable:
on: update
和xml:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:gedmo="http://gediminasm.org/schemas/orm/doctrine-extensions-mapping">
<entity name="Mapping\Fixture\Xml\Timestampable" table="timestampables">
<id name="id" type="integer" column="id">
<generator strategy="AUTO"/>
</id>
<field name="created_at" type="datetime">
<gedmo:timestampable on="create"/>
</field>
<field name="updated_at" type="datetime">
<gedmo:timestampable on="update"/>
</field>
</entity>
</doctrine-mapping>
答案 4 :(得分:1)
The other answers suggest using if
statements (which means repeating your property names) and having property-setting logic in the constructor that might never be used.
Alternatively, you could have onAdd
and onUpdate
methods that are called when needed:
/**
* @ORM\PrePersist
*/
public function onAdd()
{
$this->setAdded(new DateTime('now'));
}
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function onUpdate()
{
$this->setUpdated(new DateTime('now'));
}