2016-07-22 75 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()相反,这应该解决您的问题

相关问题