在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>
.empty可能是错的,我这样做了:
<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);
}
由于
答案 0 :(得分:3)
您必须使用$this->categories
代替$this->$categories
。后者将首先解析变量$categories
,然后尝试访问名称为该值的属性,而不是访问属性category
。
答案 1 :(得分:1)
在控制器中更改
$this->$categories
到
$this->categories
在你的树枝上:
<p>
{% for cat in advert.categories %}
{{ cat.name }}
{% else %}
No categories found...
{% endfor %}
</p>