Customers
とLocations
の2つのエンティティがあります。それらはManyToOne
の関係にあります(1人の顧客は複数の場所を持つことができます)。Twigとのドクトリン関係を扱う方法
これは私が関係を定義した方法です:
class Customers {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=45)
*/
private $name;
}
とエンティティLocations
:
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;
}
私はすべての場所をユーザーにクリックして、小枝テンプレートでレンダリングできるようにしたいです彼に関連付けられています。これが今私がやっていることですが、それが正しい方法であるかどうかはわかりません。 まずコントローラ:
<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>
どれ提案:
/**
* @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");
}
これは小枝テンプレートですか?ありがとう!
これまでのところよく見えます。しかし、$ customers_idの名前は$ customerのみにする必要があります。 – mblaettermann
通常は、Locationに1対多の関係を持つCustomer :: locationsプロパティがあります。そのようにして、顧客を積み込むことは、それ以上の努力なしに場所を与えるでしょう。製品/カテゴリの例を見てみましょう:http://symfony.com/doc/current/doctrine/associations.html#relationship-mapping-metadataあなたのケースでは、顧客はカテゴリであり、場所は製品です。将来の混乱を避け、場所の代わりに顧客と場所の代わりにエンティティの顧客名を付けます。 – Cerad