我面臨着與我的Doctrine實體關係有關的問題。 這裏的事:Symfony2從具有ManyToMany關係的倒立實體中獲取對象
我有2個實體:文章和類別 文章是高手,類是我希望得到的文章和其他方式,文章從類別分類從
。
我做了這樣的多對多關係:
class Article
{
/**
* @ORM\ManyToMany(targetEntity="Alpha\BlogBundle\Entity\Category", cascade={"persist"}, inversedBy="Article")
* @ORM\JoinTable(name="article_category")
*/
private $categories;
和
public function __construct(){
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
和在類別實體:
class Category
{
/**
* @ORM\ManyToMany(targetEntity="Alpha\BlogBundle\Entity\Article", cascade={"persist"}, mappedBy="Category")
*/
private $articles;
和
public function __construct(){
$this->articles = new \Doctrine\Common\Collections\ArrayCollection();
在我的文章的實體,我還添加了如下因素:
public function addCategory(\Alpha\BlogBundle\Entity\Category $categories)
{
$this->categories[] = $categories;
$categories->addArticle($this);
return $this;
}
(第四線,$categories->addArticle($this);
)
在我的控制器:
public function ajouterAction($data = null, $id = null) {
// On récupère l'EM pour enregistrer en BDD
$em = $this->getDoctrine()->getManager();
// On définit une nouvel objet Article avec de nouveaux attributs
$article = new Article;
$article->setTitle('1er article !');
$article->setContent('Cupcake ipsum dolor sit amet ice cream tiramisu unerdwear.com. Caramels halvah lollipop apple pie soufflé. Tart lollipop soufflé candy tootsie roll sweet donut. Lemon drops danish I love icing I love. Candy canes cheesecake I love. I love tiramisu applicake. I love gingerbread soufflé sweet roll muffin. Cupcake liquorice gummi bears muffin chocolate jelly-o.');
$article->setAuthor('Toto');
// On définit une nouvel objet Category avec de nouveaux attributs
$category = new Category;
$category->setName('Poney');
$article->addCategory($category);
$em->persist($category);
$em->persist($article);
$em->flush();
return $this->render('AlphaBlogBundle:Blog:ajouter.html.twig');
}
而完成,讓我來自類別的文章:
public function categoryAction($cat = null) {
$em = $this->getDoctrine()->getManager();
// Si cat est vide, on renvoit la liste complète des catégories
if (!isset($cat) || empty($cat) || $cat == null) {
$categories = $em->getRepository('AlphaBlogBundle:Category')->findAll();
return $this->render('AlphaBlogBundle:Blog:categories.html.twig', array(
'categories' => $categories
));
}
// Sinon on renvoit la liste des articles de la catégorie
else {
$category = $em->getRepository('AlphaBlogBundle:Category')->findOneBy(array('name' => $cat));
$articles = $category->getArticles();
return $this->render('AlphaBlogBundle:Blog:category.html.twig', array(
'articles' => $articles,
'category' => $category
//'name' => $name
));
}
}
在我看來,我可以看到我的類別的名稱,但文章沒有顯示,我有這樣的錯誤消息:
ContextErrorException: Notice: Undefined index: Category in /home/franck/www/alpha/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1036
我在這裏有點失落,如果有人可以幫助。