我有一个简单的问题,我有两个与多对多相关的表,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。我不明白我错在哪里..