Symfony 如何处理与细枝的原则关系
我有两个实体,Symfony 如何处理与细枝的原则关系,symfony,orm,doctrine,twig,Symfony,Orm,Doctrine,Twig,我有两个实体,客户和地点。他们处于manytone关系中(一个客户可以有多个地点) 这就是我定义关系的方式: class Customers { /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string", le
客户
和地点
。他们处于manytone
关系中(一个客户可以有多个地点)
这就是我定义关系的方式:
class Customers {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=45)
*/
private $name;
}
实体位置:
class Locations {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Customers", inversedBy="id")
* @ORM\JoinColumn(name="customers_id", referencedColumnName="id")
*/
private $customers_id;
/**
* @ORM\Column(type="string", length=90)
*/
private $name;
}
我希望能够点击一个用户并在一个细枝模板中呈现所有与他相关的位置。我现在就是这样做的,但我不确定这样做是否正确。
首先,控制器:
/**
* @Route("/showLocations/{id}", name = "show_locations")
* @Method("GET")
**/
public function showLocationsAction($id) {
$repository = $this->getDoctrine()->getRepository('AppBundle:Locations');
$locations = $repository->findBy(array('customer_id' => $id ));
$repository = $this->getDoctrine()->getRepository('AppBundle:Customers');
$customer = $repository->findOneById($id);
if(!empty($locations)) {
return $this->render("AppBundle:Default:showLocations.html.twig", array('locations' => $locations, 'customer' => $customer)); }
else return new Response ("There are no locations to show");
}
这是细枝模板:
<p>Locations associated with {{customer.name}}</p>
<table id="table_id" class="display">
<thead>
<tr>
<th>Locations</th>
</tr>
</thead>
<tbody>
{% for locations in locations %}
<tr>
<td>{{ locations.name|e }}</td>
</tr>
{% endfor %}
</tbody>
与{{customer.name}关联的位置
位置
{对于位置%%中的位置,}
{{locations.name | e}}
{%endfor%}
有什么建议吗?谢谢 到目前为止还不错。但是$customers\u id的命名应该仅为$customer,因为条令将自动获取相关客户并将其添加到对象中
然后您可以使用{{location.customer.name}
$repository=$this->getdoctor()->getRepository('AtlasBundle:Customers');
$customer=$repository->findOneById($id);
可以完全省略。到目前为止看起来还不错。但是命名$customers\u id应该仅为$customer。通常,您会有一个customer::locations属性,该属性与位置具有一对多关系。这样,加载客户将无需任何进一步的努力即可给出位置。看看产品/类别示例:在您的案例中,客户就是类别,位置就是产品。为了避免将来的混淆,将实体命名为Customer而不是Customers,将Location而不是Location。对不起,您的意思是将Locations私有属性$Customer\u id称为$Customer吗?内部Twig将在Locations类上查找名为::getCustomer()
的公共方法,并首先使用该方法:(请参阅“实现”部分)好的,除了{{{location.customer.name}}
部分外,它可以工作。对于键为“0,1”的数组,我得到了这个错误键为“customers”“不存在。
在模板中,如果我转储
位置,我可以看到客户的名称设置为空。我可以使用{location.0.customer.name}
打印客户名称。”。是吗?@Dygne:看起来你的映射无效。似乎每个位置都有2个客户?