我在下面创建了这两个模型(作者和书籍),通过多对多的关系相关联。然后我生成了crud方法。
问题:当我尝试使用新表单或编辑表单创建或保存作者时,它不会保存书籍。
namespace Prueba\FrontendBundle\Entity;
use \Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\Entity()
* @ORM\Table(name="author")
*/
class Author
{
/** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") **/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $name;
/**
* @ORM\ManyToMany(targetEntity="Book", inversedBy="authors")
* @ORM\JoinTable(name="author_book")
*/
protected $books;
public function __construct()
{
$this->books = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getBooks()
{
return $this->books;
}
public function addBook($book)
{
$this->books[] = $book;
}
public function setBooks($books)
{
$this->books = $books;
}
public function __toString()
{
return $this->name;
}
}
--------------
namespace Prueba\FrontendBundle\Entity;
use \Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\Entity()
* @ORM\Table(name="book")
*/
class Book
{
/** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") **/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $title;
/**
* @ORM\ManyToMany(targetEntity="Author", inversedBy="books")
* @ORM\JoinTable(name="author_book")
*/
protected $authors;
public function __construct()
{
$this->authors = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
//die("fadsfadsff");
$this->title = $title;
}
public function getAuthors()
{
//die();
return $this->authors;
}
public function addAuthor($authors)
{
die();//Here is not entering after editing a book!!!!! why????
$this->authors = $authors;
}
public function setAuthors($authors)
{
die();//Here is not entering after editing a book!!!!! why????
$this->authors = $authors;
}
public function __toString()
{
return $this->title;
}
}
答案 0 :(得分:2)
不确定这是否是问题的原因,但您在两个实体中都指定了inversedBy
。
应该是:
class Author
{
/**
* @ORM\ManyToMany(targetEntity="Book", inversedBy="authors")
*/
protected $books;
}
因为作者拥有这些书籍。
和
class Book
{
/**
* @ORM\ManyToMany(targetEntity="Author", mappedBy="books")
*/
protected $authors;
}
因为一本书属于给作者。
答案 1 :(得分:0)
级联持久性不是自动的,您没有指定任何cascade rules
/**
* @ORM\ManyToMany(targetEntity="Book", inversedBy="authors", cascade={"persist"})
* @ORM\JoinTable(name="author_book")
*/
protected $books;
我自己没有使用过与ManyToMany协会的级联,但它应该可以正常工作