0

in symfony we can access many-to-many relations with getter functions which return objects of ArrayCollection type. for example for getting Alex's students we can call $alex->getStudens(), then i have access to ale's studens object.

now my question is how i can access alex's students id's in array, for example by calling $alex->getStudentsIds() it returns {1,5,7,12,..} , which are his students's ids.

parisssss
  • 803
  • 16
  • 36
  • Knowing your end-game would probably be more helpful than providing you with a `QueryBuilder` or a custom method that returns all this stuff. Doctrine is very powerful with Object Relational Mapping and you may be trying to use an `IN` functionality for a Query where `MEMBER OF` could be a better approach. – sjagr Oct 10 '14 at 14:40

1 Answers1

0

precisely how you wrote it, you add another function in the entity

public function getStudentsIds()
{
   $students = $this->students;
   $studentIds = [];

   foreach($students as $student)
   {
     $studentIds[] = $student->getId();
   }  

   return $studentIds;
}

Ideal solution would be to add such a method to a repository and have it query only for student ids for given object but this is the simpliest solution possible.

Bartłomiej Wach
  • 1,968
  • 1
  • 11
  • 17
  • It's also possible to use indexBy when setting up your relations. In which case, a simple array_keys($students) will do the trick. – Cerad Oct 10 '14 at 15:01
  • can you give an example of the query which you say that is more efficient? thanks :) – parisssss Oct 10 '14 at 19:54
  • $repository->createQueryBuilder('q')->select('IDENTITY(q.students)')->where('q = :yourObject')->setParameter('yourObject',$yourObject) – Bartłomiej Wach Oct 10 '14 at 20:00