Note that there are some explanatory texts on larger screens.

plurals
  1. POSymfony2 - Access repository functions in Entity
    primarykey
    data
    text
    <p>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.</p> <p>I have then two entities, rabbit and carrot.</p> <p>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.</p> <p>Something like :</p> <pre><code>{% for rabbit in rabbits %} {% for carrot in rabbit.getMoreExpensiveCarrots %} {{ carrot.price }} {% endfor %} {% endfor %} </code></pre> <p>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 :</p> <p>$rabbit->getMoreExpensiveCarrots()</p> <p>I thought that a way to do that would be to create a getMoreExpensiveCarrots() in the rabbit entity :</p> <pre><code>// 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; } } </code></pre> <p>I thought I could do that too :</p> <pre><code> // Entity rabbit class Rabbit { public function getMoreExpensiveCarrots() { $this-&gt;getCarrots(); // Then try here to sort the carrots by their price, using php return $carrots; } } </code></pre> <p>Here is my controller :</p> <pre><code> public function indexAction() { $em = $this-&gt;getDoctrine()-&gt;getEntityManager(); $rabbits = $em-&gt;getRepository('AppNameBundle:Rabbit')-&gt;getSomeRabbits(); return $this-&gt;render('AppNameBundle:Home:index.html.twig', array( "rabbits"=&gt;$rabbits )); } </code></pre> <p>What is the best practise to call a getMoreExpensiveCarrots function from each rabbit in the template ?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload