我需要在数据库中保留配置文件更改的历史记录。除了配置文件数据之外,我必须保存时间戳和 user_id。创建新历史记录的查询很简单:
INSERT INTO history_profile
SELECT NULL, CURRENT_TIMESTAMP(), p.* FROM profile p WHERE p.profile_id=?
这个查询放在哪里?我无法使用触发器。我有几个想法:
在提交表单时调用的 Controller 中
$em = $this->getEntityManager(); $conn = $em->getConnection(); if (!is_null($profile->getProfileId())) { $conn->executeQuery('INSERT INTO history_profile SELECT NULL, CURRENT_TIMESTAMP(), p.* FROM profile p WHERE p.profile_id=?', array($profile->getProfileId())); } $em->persist($profile); $em->flush();
但即使配置文件没有更新,每次提交都会执行此查询。
在实体中,作为 preUpdate 的事件监听器
class Profile { /** * @ORM\preUpdate * @ORM\prePersist */ public function onPrePersist() { } }
但我不知道如何获取原则的连接对象
编辑 - EntityAudit 试用
这个 bundle 看起来很有前途,但我无法配置它。我正确安装了它,当我添加到 config.yml 时:
simple_things_entity_audit:
audited_entities:
- AldenXyzBundle\Entity\Profile
并查看之后的查询
php ./app/console doctrine:schema:update --dump-sql
但只有 SQL 用于创建表修订:
CREATE TABLE revisions (id INT AUTO_INCREMENT NOT NULL,
timestamp DATETIME NOT NULL, username VARCHAR(255) NOT NULL,
PRIMARY KEY(id)) ENGINE = InnoDB
最佳答案
您可以使用EntityAudit用于对实体进行版本控制的 bundle 。
关于Symfony2 和 Doctrine2 - 记录变更历史,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677261/