dct*_*lay 23 orm date symfony doctrine-orm
我是Symfony2(或Symfony3)的新手,我找不到如何设置doctrine(带注释配置),以便在"创建"或"修改"字段时自动将其保存在我的实体中.
dct*_*lay 39
在这之后我的解决方案......
你只需要将它直接放入你的实体类:
/**
* @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());
}
//....
}
Run Code Online (Sandbox Code Playgroud)
它实际上运作良好
Ale*_* B. 24
您可以使用StofDoctrineExtensionsBundle.这在symfony食谱中有所描述.它包含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;
Run Code Online (Sandbox Code Playgroud)
/**
*
* @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')));
}
}
Run Code Online (Sandbox Code Playgroud)
你不需要打电话__constructor.只需创建getter和setter属性created,modified就是这样.
如果您setCreated()在每次更新时首先设置,您也将更新createdcolum.所以先放setModifedAt()
还有两个例子(如果您使用的是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
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23304 次 |
| 最近记录: |