【问题标题】:Remove automatically entity in BD when choice value not selected (or null selected)未选择选项值(或选择空值)时自动删除 BD 中的实体
【发布时间】:2015-06-16 12:53:24
【问题描述】:

我想知道 symfony/doctrine 是否可以自动管理这样一个事实,即不是将我的实体的值设置为 null,而是可以简单地删除它。 (删除它是指值等于 null 的记录)

示例: 我有一个 PICTURE 实体链接到一个 VOTE 实体。每个人都可以(通过表格)投票支持或反对图片(+1 或-1)。实体 VOTE 属性值设置为 +1 或 -1。但选民也可以将他们的投票更改为支持或反对......但在这种情况下,Symfony/doctrine 不会删除实体,而是将 VOTE value_attribute 设置为 null。 (虽然我希望将其删除)。

是否可以自动完成。到目前为止,我必须在我的控制器中执行以下操作:

if($form->isValid()) 
{
  if($vote->getValue() == null)
  {
    $picture = $vote->getPicture();
    $picture->removeVote($vote);
    $em->remove($vote);
  }
}

【问题讨论】:

    标签: php forms symfony doctrine


    【解决方案1】:

    您可以使用学说实体侦听器:

    https://symfony.com/doc/current/bundles/DoctrineBundle/entity-listeners.html

    http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#entity-listeners

    里面有这样的东西:

    public function postUpdateHandler(Vote $vote, LifecycleEventArgs $event)
    {
        if (null === $vote->getValue()) {
            // Following two lines could be avoided with a onDelete: "SET NULL" in Picture orm mapping 
            $picture = $vote->getPicture();
            $picture->removeVote($vote);
            $this->em->remove($vote);
            $this->em->flush();
        }
    }
    

    您可能需要注入容器以避免循环引用异常

    【讨论】:

    • 我不明白“跟风”。您是指以下几行还是以下两行?
    • 抱歉,忘记了 w。我的意思是以下两行。
    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多