我有2个表: Product 和 Type 。关系是一种类型具有许多 Product
Type: id, name
Product: id, name, type_id
我不知道如何在Twig中显示类型名称,我是Symfony的新手,这是我的代码:
<div>
{% for pro in product %}
<div>Product name: {{ pro.name }}</div>
<div>
Type name:
</div>
<div>Price: {{ pro.price }}</div>
<div>
{% for img in pro.images %}
<img src="{{ "/uploads/product/" ~ img.path }}" style="height: 100px;">
{% endfor %}
</div>
{% endfor %}
</div>
答案 0 :(得分:3)
您可以在Twig中访问对象的属性。您不应查看数据库,而应查看实体的创建方式。您的产品具有$id
,$name
和$type
。 Type 具有$id
和$name
。
{{product.name}}
{{product.type}}
{{product.type.name}}
因此,在您的代码中,将是:
<div>
Type name: {{ pro.type.name }}
</div>
在内部,当您执行$product
时,Twig解析器将获取getName()
并检查其是否具有方法{{product.name}}
。相同的逻辑适用于{{product.type.name}}
。它检查$product
是否有getType()
,然后检查是否有getName()
。 PHP等效项为$product->getType()->getName()
。
几乎永远不要在代码中键入实际的方法。如果有必要,您可能需要退后一步并重新评估,因为它通常是code smell。
答案 1 :(得分:2)
您只需在代码中添加{{pro.type.name}}:
<div>
{% for pro in product %}
<div>Product name: {{ pro.name }}</div>
<div>
Type name: {{ pro.type.name }}
</div>
<div>Price: {{ pro.price }}</div>
<div>
{% for img in pro.images %}
<img src="{{ "/uploads/product/" ~ img.path }}" style="height: 100px;">
{% endfor %}
</div>
{% endfor %}
</div>
并确保type属性引用Type实体。您的产品实体应具有如下的type属性:
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Type", inversedBy="products")
* @ORM\JoinColumn(nullable=false)
*/
private $type;
// getter
public function getType()
{
return $this->type;
}
您的Type实体应具有如下的product属性:
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Type", mappedBy="type")
* @ORM\JoinColumn(nullable=true)
*/
private $products;
public function getProducts()
{
return $this->products;
}