Reputation: 237
I have two entities, Customers
and Locations
. They are in a ManyToOne
relationship (one customer can have multiple locations).
This is how I defined the relationship:
class Customers {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=45)
*/
private $name;
}
And the entity 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;
}
I want to be able to click on a User and render in a Twig template all the locations associated to him. This is how I'm doing that now, but I'm not sure it's the proper way. First the controller:
/**
* @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");
}
This is the twig template:
<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>
Any suggestion? Thanks!
Upvotes: 2
Views: 1880
Reputation: 1943
Looks fine so far. But naming for $customers_id should be $customer only since Doctrine will automatically fetch the related customer and hydrate it into an object.
Then you can fetch and display the customer with {{ location.customer.name }}
$repository = $this->getDoctrine()->getRepository('AtlasBundle:Customers');
$customer = $repository->findOneById($id);
Can be omitted totally then.
Upvotes: 2