2016-07-22 118 views
0

很多人會告訴我,我應該找出一種方法來更好地在我的桌子上進行關係,但我有一個'產品'表和一個'product_images'表很容易加入到查詢中,但是因爲圖像的路徑可能會有根本的不同,我不想在表中存儲路徑名,所以我需要一個函數來進行一些計算以找出路徑。我需要爲每個產品運行該方法,因爲我正在遍歷每個產品以獲取映像的路徑。如何從Twig調用實體方法

我想做什麼,也許我沒有正確的思想,是在嫩枝我想問的方法爲產品實體

{% for product in products %} 
    {{product.getImageUrl()}} 
{% endfor %} 

這將調用的方法運行我的產品實體

//AppBundle:Entity:Product 
public function getImageUrl() 
{ 
    $repository = $this->getDoctrine()->getRepository('AppBundle:Product'); 
    return $repository->getImagePath($this->id); 
} 

在我的倉庫:

//AppBundle:Repositiories:ProductRepository 
public function getImagePath($id) 
{ 
    return 'http://domain.com/path/to/image.jpg'//simplified for my question 
} 

我怎樣才能做到這一點?當我嘗試這樣的時刻,我收到以下錯誤:

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in product/index.html.twig at line 19. 

,其中第19行是

<img src="{{product.getImageUrl()}}" alt="img"> 

如何可以完成使用從實體的方法?或者告訴我,我還能如何做到這一點。提前致謝。

+1

你真的應該弄清楚如何做你的關係更好。開玩笑。你的樹枝是正確的。 Product :: getImageUrl()只是返回一個簡單的字符串來證明它。你的產品實體全部搞砸了。沒有辦法讓容器可以訪問它。你可能需要像ProductImagManager :: getImageUrl($ product)之類的東西,然後通過樹枝擴展在樹枝中訪問它。我假設你實際上正在傳遞一組產品實體,而不是一組產品數組。這就是你的錯誤信息似乎表明的內容。 – Cerad

+1

{{product.imageUrl}}? – Alsatian

回答

0

您的問題的答案在錯誤消息中是正確的。 正如它向您解釋的那樣,小枝不能將數組轉換爲字符串。現在爲什麼我們甚至有一個數組?

我假設,在您的public function getImagePath($id)方法中,您最後調用getResult()以獲取所需的圖像路徑。但是,getResult總是返回結果數組,即使只有一個結果。

如果你確信你會得到結果只有一個,嘗試調用getOneOrNullResult()相反,這應該解決您的問題

相關問題