symfony2 doctrine findBy id in arrayCollection

会有一股神秘感。 提交于 2019-12-23 02:57:19

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/22722926/symfony2-doctrine-findby-id-in-arraycollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!