【发布时间】:2016-07-22 22:52:07
【问题描述】:
你们中的很多人会告诉我,我应该想办法在我的表中更好地建立关系,但是我有一个“products”表和一个“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">
如何使用实体中的方法来完成?或者告诉我我还能怎么做。提前致谢。
【问题讨论】:
-
你真的应该弄清楚如何更好地处理你的关系。只是在开玩笑。你的树枝是正确的。让 Product::getImageUrl() 返回一个简单的字符串来证明它。你的产品实体都搞砸了。您无法在其中访问容器。您可能需要 ProductImagManager::getImageUrl($product) 之类的东西,然后通过 twig 扩展在 twig 中访问它。我假设您实际上传递的是产品实体数组而不是产品数组数组。您的错误消息似乎表明了这一点。
-
{{ product.imageUrl }} ?
标签: symfony doctrine-orm twig