【问题标题】:Related entities don't save to a database Symfony2相关实体不保存到数据库 Symfony2
【发布时间】:2014-12-18 09:45:21
【问题描述】:

我有一个通过多对多关系关联的两个实体,以及具有实体字段类型的表单构建器,但所有这些都没有保存到数据库中。这是我的文件的链接。有人可以帮助我。我的错在哪里?

链接:

tag entity

post entity

contorller action

form_builder

【问题讨论】:

  • $this->save($post); 在您的控制器操作中指的是什么?此控制器中没有 save() 方法。或者你只是忘记粘贴它,我们看不到它。
  • @VaN,此方法只需调用实体管理器 persit $post 并将其刷新到数据库。
  • 我很确定您不必在控制器中使用这个 foreach() 循环。表单类型和请求处理程序应该为您完成这项工作。你应该完整阅读这个 symfony 食谱教程:symfony.com/doc/current/cookbook/form/form_collections.html 它从头到尾完成了你想要达到的目标。实际上,您的数据库中当前保存的是什么?没有 ?只发帖?
  • @VaN,只发帖。如果没有 foreach 相同的结果,关系不会保存。
  • 我认为你的问题是你没有级联持久性。看看我上面链接的cookbook页面,在页面中搜索“Doctrine: Cascading Relations”。

标签: symfony orm doctrine-orm entity entity-relationship


【解决方案1】:

尝试在表单中将 'by_reference' 设置为 false :

->add('tags', 'entity', array(
                    'label' => 'Tags',
                    'class' => 'GeekhubMainBundle:Tag',
                    'property' => 'tagName',
                    'empty_value' => 'Choose a tag',
                    'multiple' => true,
                    'expanded' => false,
                    'by_reference' => false, // Makes sure that tags 
                                             // are actually added to your post
                    'query_builder' => function (TagRepository $repository) {
                            return $repository->findEnabledTags();
                        }
                )

这是您在 Symfony Cookbook 中尝试实现的目标的示例:http://symfony.com/doc/current/cookbook/form/form_collections.html

还有一些关于by_reference的信息:http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference

【讨论】:

    【解决方案2】:

    像这样改变你的实体:

    标记实体:

     /**
     * @param Post $post
     * @return $this
     */
    public function addPost(Post $post)
    {
        $post->addTag($this);
        $this->posts->add($post);
    
        return $this;
    }
    

    发布实体:

    /**
     * @param Tag $tag
     * @return $this
     */
    public function addTag(Tag $tag)
    {
        $tag->addPost($this);
        $this->tags->add($tag);
    
        return $this;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多