我有一个简单的问题, 我有两个关于多对多的表,帖子和类别, 在一个完整的形式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。 我不明白我哪里错了..
答案 0 :(得分: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