ManyToMany关系:数据已正确保存但无法显示:类别为空


ManyToMany relation: data correctly saved but cannot be shown : categories is empty?

在ManyToMany关系(广告和类别)中,数据库中充满了数据,但当我试图在Twig中显示结果时,我遇到了这个错误,它说:

致命错误:无法访问空属性

class Advert:中的这条线上

public function getCategories(){
    return $this->$categories;
}

这是Twig页面:

    <p>
{% if not advert.categories.empty %}
{% for cat in advert.categories %}
  {{ cat.name }}{% if not loop.last %}, {% endif %}
{% endfor %}
{% endif %}
</p>

.空可能是错误的,我这样做了:

<p>
      {% if listCategories|length>0 %}
    listcat
    {% for list in listCategories %}
      {{ list.name }}{% if not loop.last %}, {% endif %}
    {% endfor %}
    {% endif %}
  </p>

但错误是一样的。

这是代码:

public function addAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$advert = new Advert();
$advert->setTitle('title');
$advert->setAuthor('author');
$listCategories = $em->getRepository('OCPlatformBundle:Category')->findAll();
  foreach ($listCategories as $category) {
    $advert->addCategory($category);
  }
$em->persist($advert);
$em->flush();
return $this->redirect($this->generateUrl('oc_platform_view', array('id'=>$advert->getId())));
}

public function viewAction($id)
{
  $em = $this->getDoctrine()->getManager();
  $advert = $em->getRepository('OCPlatformBundle:Advert')->find($id);
  /*or :
  $listCategories = $em
          ->getRepository('OCPlatformBundle:Advert')
          ->getAdvCategories();
  */

  return $this->render('OCPlatformBundle:Advert:view.html.twig', array(
    'advert' => $advert
  ));
  //or with : 'listCategories' => $listCategories
}
//in the advert repository
public function getAdvCategories(){
    $qb = $this
            ->createQueryBuilder('a')
            ->join('a.categories', 'c')
            ->addSelect('c');
    return $qb->getQuery()->getResult();
}

class Advert {
    public function __construct(){
        $this->categories = new ArrayCollection();
    }
    public function getCategories(){
        return $this->$categories;
    }
    public function addCategory(Category $cat){
        $this->categories[] = $cat;
        return $this;
    }
    public function removeCategory(Category $cat){
        $this->categories->removeElement($cat);
    }

感谢

您必须使用$this->categories而不是$this->$categories。后者将首先解析变量$categories,然后尝试访问具有该值名称的属性,而不是访问属性category

在控制器中更改

$this->$categories

$this->categories

在你的树枝上:

<p>
{% for cat in advert.categories %}
  {{ cat.name }}
{% else %}
  No categories found...
{% endfor %}
</p>