如何在Symfony 4的Twig中显示数据库表?属性访问错误求助
问题分析与解决方案
首先看你遇到的错误:Neither the property "product_code" nor one of the methods "product_code()", "getproduct_code()"/"isproduct_code()"/"hasproduct_code()" or "__call()" exist...,这是因为Twig访问实体属性的方式和你写的不匹配,加上代码里还有几个小问题,我帮你一步步解决:
核心错误原因
- 实体属性访问方式错误:你的
NewProduct实体里,私有属性是$product_code,但对应的getter方法是getProductCode()(驼峰命名)。Twig在访问{{ newproduct.product_code }}时,会优先找公开的product_code属性(但你的是私有),然后找getproduct_code()方法(注意是全小写开头,和你的getProductCode()不匹配),所以找不到。 - 循环变量名冲突:你写的
{% for newproduct in newproduct %}会把循环的单个产品对象覆盖掉原本的newproduct数据集,导致循环过程中后续访问出错。 - 冗余的分类循环:每个产品都遍历所有分类完全没必要,因为你的实体已经通过
ManyToOne关联了单个分类,直接访问产品的关联分类即可。
修正后的Twig代码
<div class="table-responsive"> <table class="table table-condensed" border="1" cellpadding="10"> <tbody> <tr> <th><h4> ID</h4></th> <th><h4> category</h4></th> <th><h4> product_code</h4></th> <th><h4> product_name</h4></th> <th><h4> quantity</h4></th> <th><h4> price</h4></th> <th><h4> gst </h4></th> <th><h4> hsn_code</h4></th> <th><h4> product_metric </h4></th> <th><h4> product_dimension </h4></th> <th><h4> supplier_name</h4></th> </tr> {% for product in newproducts %} {# 重命名循环变量,避免覆盖数据集 #} <tr> <td> {{ product.id }} </td> {# 对应实体的getId()方法 #} <td> {{ product.category.category }} </td> {# 直接访问关联的分类对象属性 #} <td> {{ product.productCode }} </td> {# 对应getProductCode()方法 #} <td> {{ product.productName }} </td> {# 对应getProductName()方法 #} <td> {{ product.quantity }} </td> {# 对应getQuantity()方法 #} <td> {{ product.price }} </td> {# 对应getPrice()方法 #} <td> {{ product.gst }} </td> {# 对应getGst()方法 #} <td> {{ product.hsnCode }} </td> {# 对应getHsnCode()方法 #} <td> {{ product.productMetric }} </td> {# 对应getProductMetric()方法 #} <td> {{ product.productDimension }} </td> {# 对应getProductDimension()方法 #} <td> {{ product.supplierName }} </td> {# 对应getSupplierName()方法 #} </tr> {% endfor %} </tbody> </table> </div>
关键修改点说明
- 循环变量重命名:把
{% for newproduct in newproduct %}改成{% for product in newproducts %}(后端传参时也要对应把数据集变量名改为newproducts,或者保持原名但循环变量用item这类不同名称),避免变量覆盖导致的访问异常。 - 实体属性访问改为驼峰式:比如
product_code改成productCode,Twig会自动匹配对应的驼峰命名getter方法(规则:productCode对应getProductCode(),id对应getId()),这样就能正确获取私有属性的值。 - 移除冗余的分类循环:直接用
{{ product.category.category }}获取当前产品关联的分类名称,因为你的NewProduct实体已经通过ManyToOne关联了单个Category对象,不需要遍历所有分类。
另外要确保后端控制器正确传递数据集,示例代码如下:
// 控制器中传递数据到Twig $newproducts = $entityManager->getRepository(NewProduct::class)->findAll(); return $this->render('your_template.html.twig', [ 'newproducts' => $newproducts, ]);
这样修改后,就能正确渲染newproduct表的数据了。
内容的提问来源于stack exchange,提问作者viveka
相关产品推荐
相关产品推荐

