2012-04-12 50 views
1

早些时候我使用了Symfony 1.4。现在我学习的Symfony 2.我做的:http://symfony.com/doc/current/book/doctrine.html 和我有:与TWIG的关系

class Product 
{ 

    /** 
    * @ORM\ManyToOne(targetEntity="Category", inversedBy="products") 
    * @ORM\JoinColumn(name="category_id", referencedColumnName="id") 
    */ 
    protected $category; 

    //... 
} 

class Category 
{ 

    /** 
    * @ORM\OneToMany(targetEntity="Product", mappedBy="category") 
    */ 
    protected $products; 

    public function __construct() 
    { 
     $this->products = new ArrayCollection(); 
    } 
    //... 
} 

在Symfony的1.4英寸的foreach我可以使用:

$result = findAll from Products. 
foreach ($results as $result){ 
    echo $result->getCategory()->getName(); 
} 

我怎样才能得到与TWIG系统的关系(在本例中是Category)?

{% for item in results %} 
       <li><a href="{{ item.id }}">{{ item.name }} --- {{ item.category }} {{item.category.name}}</a></li> 
      {% endfor %} 

item.category和item.category.name不起作用。我无法在文档中找到它。

编辑:

OK,现在我知道了。我没有一个产品的关系。在此之前我如何保护?

我有:

id | name | category 
1 | first | 1 
2 | second | NULL 
3 | third | 2 

如果每一行类别不是null,则此工作正常,但如果我的关系有NULL的话,我有错误:

Item "name" for "" does not exist in AcmeStoreBundle:Default:index.html.twig at line 3 

什么我可以做有了这个?

+0

看来,有什么东西与你的关系中断了。我有类似的东西,{{article.user.name}}'工作正常。 – KingCrunch 2012-04-12 08:23:09

+0

你的例子在哪里? :) – 2012-04-12 08:26:09

+0

哪个例子?我只是想告诉你,你的'{{item.category.name}}''应该工作,我想,你的问题必须在更早的地方 – KingCrunch 2012-04-12 08:49:19

回答

3

将此添加到要输出名称的位置。这将防止枝条抛出该错误。

{% if item.category.name is defined %} 
    {# print the name here #} 
{% endif %}