gpt4 book ai didi

symfony - 如何在 Symfony2 中处理 SQL 触发器?

转载 作者:行者123 更新时间:2023-12-02 16:09:44 24 4
gpt4 key购买 nike

我有一个User我的 Symfony2/Doctrine2 web 应用程序中的实体。该用户具有属性 last_updated确定最近的时间,任何事情都发生了变化。我将此属性设置为 NOT NULL在我的数据库中。到目前为止,一切顺利。

我认为在数据库中创建一个 SQL 触发器是一个很好的做法,它设置了 last_updatedNOW()INSERTUPDATE 。所以您不必在应用程序中关心这一点。这就是我所做的,我在我的数据库中实现了这个触发器。

但是如果我现在在我的应用程序中创建一个用户

$user = new User();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();

我收到 Symfony 的错误消息:

An exception occurred while executing 'INSERT INTO User (username, ..., last_updated) VALUES (?, ..., ?)' with params ["johndoe", ..., null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'last_updated' cannot be null

问题很明显:Symfony 正在尝试触发 INSERT -使用参数null对数据库进行语句对于 last_updated ,这是不允许的 - 因为此属性可能不为空。

我很快就想到了两种解决方法:

  • 一种解决方法是采用 last_updated实体描述之外的字段。然后 Symfony 不会尝试将此列的任何内容传递到数据库,并且触发器将设置适当的值。但我认为这不是一个好方法,因为一旦我尝试更新数据库架构( doctrine:schema:update --force ),我就会丢失我的 last_updated 。 -列。
  • 另一种解决方法:只需执行 $user->setLastUpdated(new \DateTime())在我之前persist()flush() 。但这会最大限度地减少在数据库上使用触发器以避免在应用程序中关心它的优势。

有什么方法可以让 Symfony/Doctrine 知道我的数据库上正在运行触发器吗?如果没有,(如何)我可以连接到 Symfony/Doctrine 来实现适当的解决方法?

最佳答案

引用 Google 群组对此问题的回复:

Database side code (such as Triggers and Functions) tend to break the benefits of developing software using an ORM like Propel or Doctrine as one of the biggest advantages of using ORM's is to be database agnostic. By having database side Triggers and Functions you are tying yourself to the database and therefore gain little to no benefit using an ORM. -GarethMc

https://groups.google.com/forum/#!topic/symfony-users/MH_ML9Dy0Rw

为此,最好按照 Faery 的建议使用生命周期回调。一个简单的函数将处理该字段的更新,这样如果您决定将来更改数据库,就不必担心它。

//In Your Entity File EX: SomeClass.php
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class SomeClass
{
....

/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function prePersistPreUpdate()
{
$this->last_modified = new \DateTime();
}
}

另请参阅生命周期回调引用

在您的情况下,您可以将生命周期回调函数和注释添加到您的 User 实体类中。 SomeClass 只是一个示例类,它显示生命周期回调不仅仅适用于您的 User 实体。

关于symfony - 如何在 Symfony2 中处理 SQL 触发器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18377690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com