2012-04-12 54 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 %}