2017-02-01 8 views
1

CustomersLocationsの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"); 
} 

これは小枝テンプレートですか?ありがとう!

+0

これまでのところよく見えます。しかし、$ customers_idの名前は$ customerのみにする必要があります。 – mblaettermann

+1

通常は、Locationに1対多の関係を持つCustomer :: locationsプロパティがあります。そのようにして、顧客を積み込むことは、それ以上の努力なしに場所を与えるでしょう。製品/カテゴリの例を見てみましょう:http://symfony.com/doc/current/doctrine/associations.html#relationship-mapping-metadataあなたのケースでは、顧客はカテゴリであり、場所は製品です。将来の混乱を避け、場所の代わりに顧客と場所の代わりにエンティティの顧客名を付けます。 – Cerad

答えて

2

これまでのところよく見えます。しかし、$ customers_idの名前はDoctrineが自動的に関連顧客を取得し、それをオブジェクトに含めるので、$ customerでなければなりません。

次にあなたが{{ location.customer.name }}

$repository = $this->getDoctrine()->getRepository('AtlasBundle:Customers'); $customer = $repository->findOneById($id);

で顧客を取得し、表示することができますが、完全を省略することができます。

+0

申し訳ありませんが、Locationsのプライベートプロパティ$ customer_idを$ customerと呼んでいますか? – Dygne

+0

内部では、Locationsクラスの ':: getCustomer()'というパブリックメソッドを探し、それを最初に使用します:http://twig.sensiolabs.org/doc/2.x/templates.html(「実装」を参照)セクション) – mblaettermann

+0

これは、 '{{location.customer.name}}'部分を除いて動作します。私はこのエラーを受け取ります。キー "0、1"が存在しない配列のキー "得意先"はありません。テンプレートでは、場所を 'ダンプする 'とすれば、' Customers'の名前がnullに設定されています。 – Dygne

関連する問題