Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first entity from linked entity

I have the

Class User  {

@OneToMany
    private $profiles
}

Now I have the $user entity in my controller but I also want the first or last profile based on date. How can I achieve this?

I have the method getProfiles() but I think that will return the array collection.

like image 767
Mirage Avatar asked Aug 01 '12 01:08

Mirage


2 Answers

$user->getProfiles()->first()

will do it, as long as you are declaring the $profiles property as a

\Doctrine\Common\Collections\ArrayCollection

in the constructor of your class.

like image 136
Lusitanian Avatar answered Nov 16 '22 03:11

Lusitanian


You can easily get the first one like that :

$first = $this->get('doctrine.manager')->getRepository(MyEntity::class)->findOneBy([]);
like image 26
user1097795 Avatar answered Nov 16 '22 02:11

user1097795