Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last element of a OneToMany relation with Doctrine

I'm having a "Student" model that is related to many "Transfer" elements in Symfony2 using Doctrine.

How can I access the last "Transfer" element that is related to the current "Student" in an efficient way?

That is to say for example, creating a method like "getLastTransfer()" in the "Student" class.

I have hears that it is not recommended to use the entity manager inside of a modal in order to be able to use dependency injections on it etc...

Thank you

like image 564
Yassir Ennazk Avatar asked Sep 03 '12 01:09

Yassir Ennazk


1 Answers

Granted that your Transfer entity has a date field, Student class will look like:

class Student
{
    // ...

    /**
     * @OneToMany(targetEntity="Transfer" mappedBy="student")
     * @OrderBy({"date" = "ASC"})
     */
    private $transfers;

    // ...

}

The transfers are stored in a ArrayCollection, so just call:

$student -> getTransfers() -> last();
like image 115
moonwave99 Avatar answered Nov 07 '22 08:11

moonwave99