Symfony2,关系表格中的manyToMany

时间:2014-02-12 19:06:39

标签: symfony doctrine-orm many-to-many symfony-forms

我开始学习sf2,非常酷,因为我的问题我有两张桌子:

媒体

/**
 * @ORM\ManyToMany(targetEntity="Test\SiteBundle\Entity\Website", inversedBy="medias")
 * @ORM\JoinTable(name="media_website")

private $websites;

网站

/**
 * @ORM\ManyToMany(targetEntity="Test\SiteBundle\Entity\Media", mappedBy="websites")

private $medias;

在我的MediaType.php中,我有这个:

$builder
        ->add('title')
        ->add('website', 'entity', array(
            'class'         =>  'TestSiteBundle:Website',
            'property'  =>  'name',
            'query_builder' => function(WebsiteRepository $er)use($user_id) {
                               return $er->getMyWebsites($user_id);
             },
            'multiple'=>false))

最后,在枝条页面中我有这个:

<div class="form-group">
   {{ form_label(form.description, "Description", { 'label_attr': {'class': 'control-label col-md-2'} }) }}
   <div class="col-md-5">
        {{ form_widget(form.description, { 'attr': {'class': 'form-control'} }) }}
   </div>
</div>

当我尝试添加媒体时出现此错误:

Neither the property "websites" nor one of the methods "setWebsites()", "__set()" or "__call()" exist and have public access in class "Test\SiteBundle\Entity\Media". 

有任何帮助吗?非常感谢你。

2 个答案:

答案 0 :(得分:5)

我发现,对于有相同问题的人,在ManyToMany关系中你需要在FormType中有 multiple =&gt; true ,所以我的MediaType应该是:

$builder

        ->add('websites', 'entity', array(
            'class'         =>  'EveadSiteBundle:Website',
            'property'  =>  'name',
            'query_builder' => function(WebsiteRepository $er)use($user_id) {
                               return $er->getMyWebsites($user_id);
             },
            'multiple'=>true))

答案 1 :(得分:0)

将两个类的属性设置为protected而不是private,以允许doctrine在其Proxy类中访问它们。

您还需要添加公共getter和setter方法,以便在应用程序中访问模型上的数据。您可以使用Symfony控制台的doctrine:generate:entities命令 - see documentation here

相关问题