以数组格式symfony2访问多对多关系 [英] Access to many-to-many relation in array format, symfony2
问题描述
在symfony中,我们可以使用getter函数访问多对多关系,该函数返回ArrayCollection类型的对象。以
为例,为了吸引Alex的学生,我们可以调用 $ alex-> getStudens()
,然后我可以访问ale的studens对象。
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.
现在我的问题是如何访问数组中alex的学生证,例如通过调用 $ alex-> getStudentsIds()
返回{1,5,7,12,..},这是他的学生的ID。
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.
推荐答案
确切地讲,您是在实体中添加另一个函数
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;
}
理想的解决方案是将这种方法添加到存储库中并查询仅适用于给定对象的学生ID,但这是最简单的解决方案。
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.
这篇关于以数组格式symfony2访问多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!