symfony2 doctrine findBy id in arrayCollection

jmiguel picture jmiguel · Mar 28, 2014 · Viewed 13.1k times · Source

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...

Answer

dmnptr picture dmnptr · Mar 28, 2014

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();
}