【问题标题】:How to update entities through a relationship with Symfony?如何通过与 Symfony 的关系更新实体?
【发布时间】:2014-08-17 20:15:51
【问题描述】:

我的 Symfony 应用程序中有一个 article 实体和一个 tag 实体。我有一个嵌套表单来编辑和标记文章:

当我从这个表单添加一个新标签时,Doctrine 会尝试将一个新标签插入到Tag 表中,而不是在连接表中插入一个新关系,即article_tag,这会导致违反唯一名称约束。为了纠正这个问题,我创建了一个data transformer,它获取并返回任何现有的Tag 对象:

public function reverseTransform($name)
{
    //…

    return $this->om
        ->getRepository('AcmeBundle:Tag')
        ->findOneByName($name)
    ;
}

不幸的是,应用程序将其转换回字符串(DBAL/Statement.php 第 103 行),因此 Doctrine 仍然启动相同的插入查询。我怎样才能防止这种情况?我应该在哪里查找任何错误?

请检查 ArticleType.php 和 TagType.php 在我关于 reusing existing entities 表单的 Type 文件 和两个实体的问题中我对协会的avoiding duplicate entries with Doctrine 的问题!我需要保留新标签(它有效)并为新关系选择已经持久的标签。很长一段时间以来,我一直在努力完成这项任务。

【问题讨论】:

  • 请发布您的表单类型文件以及您与两个实体的关联。您是否还需要保留不存在的标签,还是只需要选择已经保留的标签?

标签: php symfony doctrine-orm


【解决方案1】:

ArticleType中可以设置标签不映射:

$builder->add('tags', 'text', array(
    //...
    'mapped' => false
));

然后你可以在你的控制器中获取标签的值,你可以找到它的现有实体。然后你可以将这些标签设置为你的Article:

$data = $form->getData();
// now $data['tags'] are the tags
// ... Get the tags entities by Doctrine and set them to the article
$article->addTag($tag);

(当然要在Article.php中实现addTag()方法。)

你只是简单地persist()然后flush(),关系就被正确保存了。

【讨论】:

    【解决方案2】:

    在您的 ArticleType.php 中试试这个:

        $builder->add('tags', new TagType(), array(
            //...
           'by_reference' => false,
        ));
    

    为您添加标签自动完成检查此捆绑包https://github.com/PUGX/PUGXAutoCompleterBundle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 2021-07-16
      相关资源
      最近更新 更多