1

Using Symfony2.3.4 and Doctrine.

I have a class Student with a ManyToMany relation with a class Edition.

Now in my StudentController I have this IndexAction($edition_id) to list not all students in the DB but only those related to the given Edition id.

$entities = $em->getRepository('PersonBundle:Student')->findBy(array(
    ????????
));

I'm thinking of some kind of criteria to use with $edition_id but can't come up with any.

Tips appreciated, thanks.

@dmnptr: I'm trying that, I'm quite new to this so tell me if I did something wrong.

I put that function you wrote in the controller and in the method IndexAction($edition) I added

$students = this->findAllByEdition($edition);

now the problem is that the parameter $edition is coming from a twig template like this:

<a href="{{ path('student', { 'edition': entity}) }}"</a>

being entity who holds the Edition object.

But when I do it like this entity returns the __toString() method, meaning a string with the name of the edition, not the edition itself which is what the function you gave me uses.

Now, do you happen to know a way to get the object itself from the template, not the __toString() method, thanks...

jmiguel
  • 296
  • 2
  • 5
  • 15
  • You cannot squeeze the whole object into URL. You should use `entity.id` in `path()`, and then in your controller get the entity you need using its id. Also, `findAllByEdition` should go into custom repository, not controller. – dmnptr Mar 28 '14 at 23:42
  • that's what I thought, only I don't know how to call the method if it is not in the controller, can you tell me? And also, and this is just to be sure, what would be a risk of leaving it in the controller?? – jmiguel Mar 29 '14 at 07:29
  • I don't think that there is a risk associated with having this method in a controller. You can do that, it is your choice. However, this is considered a bad style as it adds the code that logically belongs to a repository to your controller making it unnecessarily big. Here is more about custom repository: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes – dmnptr Mar 31 '14 at 15:16

1 Answers1

4

You should use custom repository method. Pass $edition as a parameter, not just an id. Something like this:

public function findAllByEdition($edition)
{
    $em = $this->getEntityManager();

    $queryText  = "SELECT s FROM PersonBundle:Student s ";
    $queryText .= "WHERE :edition MEMBER OF s.editions";

    $query = $em->createQuery($queryText);
    $query->setParameter('edition', $edition)

    return $query->getResult();
}
dmnptr
  • 4,258
  • 1
  • 20
  • 19
  • works just fine only, at least in my case, it works with the entity's id,not the entity object itself, meaning: findAllByEdition($edition_id) is ok. – jmiguel Mar 29 '14 at 01:20
  • Even better - less database queries :-) – dmnptr Mar 31 '14 at 15:18