Let’s say that I have two tables in my database : Rabbits and Carrots.
Rabbits can have 0 or multiples carrots and a carrot belongs to a single rabbit. That’s a 1,n relation between those two tables.
I have then two entities, rabbit and carrot.
I have an array of rabbits passed in my template and I would like to get specific carrots from each rabbit an display them : let’s say I want to get the 10 more expensive carrots (carrots prices would be stored in the carrots table) from each $rabbit in the array.
Something like :
{% for rabbit in rabbits %}
{% for carrot in rabbit.getMoreExpensiveCarrots %}
{{ carrot.price }}
{% endfor %}
{% endfor %}
I’m using repository class, but if i create a function getMoreExpensiveCarrots( $rabbit ) in a rabbit repository class, I would not be able to access that function from an entity class like that, which is what I want :
$rabbit->getMoreExpensiveCarrots()
I thought that a way to do that would be to create a getMoreExpensiveCarrots() in the rabbit entity :
// Entity rabbit
class Rabbit
{
public function getMoreExpensiveCarrots()
{
// Access repository functions like getMoreExpensiveCarrots( $rabbit )
// But how can I do such thing ? Isn't that bad practise ?
return $carrots;
}
}
I thought I could do that too :
// Entity rabbit
class Rabbit
{
public function getMoreExpensiveCarrots()
{
$this->getCarrots();
// Then try here to sort the carrots by their price, using php
return $carrots;
}
}
Here is my controller :
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$rabbits = $em->getRepository('AppNameBundle:Rabbit')->getSomeRabbits();
return $this->render('AppNameBundle:Home:index.html.twig',
array(
"rabbits"=>$rabbits
));
}
What is the best practise to call a getMoreExpensiveCarrots function from each rabbit in the template ?
Thanks!
Back to basics. Forget about repository vs service and just focus on rabbits and carrots.
Remove all the carrot stuff from your query and just get a list of rabbits.
Your original template will now work exactly as expected:
The only downside here is that for each rabbit, a separate query for all carrots will be automatically generated by Doctrine. At some point performance will be hindered. When you reach that point then you can go back to your original query and see how to bring the carrots in more efficiently. But get the above class working first as I think this might be your blocking point.