Access to many-to-many relation in array format, symfony2

拟墨画扇 提交于 2019-12-12 02:26:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26301598/access-to-many-to-many-relation-in-array-format-symfony2

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