0

我有一个简单的问题,我有两个与多对多相关的表,Post 和 Category,完整的 PostType 形式是 CategoryType 的集合,但是问题从这里开始......

我按照说明书收集表单上的说明来保存数据,我只是没有得到想要的结果。这是代码:

class Post
{
/**
 * 
 * @ORM\ManyToMany(targetEntity="Categories", inversedBy="posts", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="AnCat",
 *  joinColumns={
 *     @ORM\JoinColumn(name="post_id", referencedColumnName="id")
 *  },
 *  inverseJoinColumns={
 *     @ORM\JoinColumn(name="categories_id", referencedColumnName="id")
 *  }
 * )
 **/
protected $categories;

public function __construct()
{
    $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}

public function addCategory($categories)
{
    foreach ($categories as $category) {
        $category->addPosts($this);
    }
    $this->categories[] = $categories;
}

class Categories
{
/**
 * 
 * @ORM\ManyToMany(targetEntity="Post", mappedBy="categories")
 */
protected $posts;

public function __construct()
{
    $this->posts = new ArrayCollection();
}

/**
 *
 * @param Post $post
 * @return Categories
 */
public function addPosts(Post $posts)
{
   // I tried it but I get the same result!
   /*if (!$this->posts->contains($posts)) {
        $this->posts->add($posts);
    }*/

    $posts->addCategory($this);
    $this->posts[] = $posts;
}

class PostType extends AbstractType
{

->add('Categories', 'collection', array('type' => new CategoriesType(), 
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => true,
                'prototype_name' => '__categ__',
                'by_reference' => false
            ))

class CategoriesType extends AbstractType
{
     ->add('category', 'entity', array(
            'attr' => array('class' => 'cat'),
            'class' => 'MyBusinessBundle:Categories',
            'property' => 'category',
            'label' => 'Categories'
        ))

问题是插入一个新的字段Category,而不是创建一个简单的关系Post-Category。我不明白我错在哪里..

4

1 回答 1

1

在您的 postType 中,将集合类型更改为实体类型

    class PostType extends AbstractType
    {
    $builder->add('Categories', 'entity',
        array( 'label' => 'Categories',
            'required' => false,
            'expanded' => true,
            'class' => 'xxx\xxxBundle\Entity\Categories',
            'property' => 'title',
            'multiple' => true,
        ));

在您的帖子创建表单中,您将拥有带有类别的复选框。如果您想要一个多选字段,请更改扩展为 false

于 2013-03-14T12:09:42.987 回答