如何在symfony2表单中映射多对多的关系?

时间:2015-01-20 06:23:21

标签: php symfony

我创建了博客包,我创建了以下实体。

1.post
2.postcategoryinfo
3.posttaginfo
4.category
5.tag

在帖子形式中,在帖子实体中没有字段的类别和标签多选择下拉列表。

一旦帖子在同一帖子中创建了多个类别和多个标签选择。该条目在 postcategoryinfo表中完成,用于类别映射,如:

IN POST 1 I SELECT 2 CATEGORY

IN post TABLE ID 1 INSERTED
id    name
1     Post1  

IN postcategoryinfo TABLE 
post_id   category_id
1            1
1            2

same way in posttaginfo tabel 
post_id   tag_id
1            1
1            2

如何以邮寄形式在这三张表格之间建立关系。

在编辑时,如何在下拉菜单中选择此类别和标签。

1 个答案:

答案 0 :(得分:2)

在你的帖子实体后面的字段中需要添加:

    /**
     * @ORM\ManyToMany(targetEntity="Com\YourBundle\Entity\Category", inversedBy="postcatagory")
     * @ORM\JoinTable(name="postcategoryinfo",
     *      joinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
     *      )
     */
    private $category;

    /**
     * @ORM\ManyToMany(targetEntity="Com\YourBundle\Entity\Tag", inversedBy="posttag")
     * @ORM\JoinTable(name="posttaginfo",
     *      joinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id")}
     *      )
     */
    private $tag;

在您的类别实体中:

    /**
     * @ORM\ManyToMany(targetEntity="Com\YourBundle\Entity\Post", mappedBy="category")
     */
    private $postcategory;

在您的代码实体中:

    /**
     * @ORM\ManyToMany(targetEntity="Com\YourBundle\Entity\Post", mappedBy="tag")
     */
    private $posttag;

在你的postType中:

     ->add('category', NULL, array(
            'label' => 'Category',
            'class' => 'YourBundle:Category',
            'property' => 'category_name', // Whatever your field name
       }))
     ->add('tag', NULL, array(
            'label' => 'Tag',
            'class' => 'YourBundle:Tag',
            'property' => 'tag_name', // Whatever your field name
       }))

现在,您可以按照自己的方式渲染Post表单。它将使用多选组合创建和编辑它。