我有两个实体,event
和 participant
。他们有一个关系,就像每个事件都可以有很多参与者一样。
participants
具有选中、可见等属性。
正常情况下,我可以在我的控制器中做一些类似的$event->getParticipant();
。
现在获得更具体选择的最佳方法是什么? 例如,我想实现以下一些功能:
$event->getVisibleParticipant();
$event->getCheckedParticipant();
$event->getVisibleAndCheckedParticipant();
如何以及在哪里以最佳方式实现这些功能?
我试图实现一个事件存储库,但它说我想在那里调用的方法未定义......
你可能最好地用 Doctrine 的集合filter
方法来实现这一点
http://api.nellafw.org/class-Doctrine.Common.Collections.ArrayCollection.html
因此,在您的Event
实体上,假设您的关系如下所示
<?php
namespace /Your/Bundle/Entity;
use DoctrineORMMapping as ORM;
use DoctrineCommonCollectionsArrayCollection;
/**
* @ORMTable()
* @ORMEntity()
*/
class Event
{
/**
* @ORMOneToMany(targetEntity="Participant", mappedBy="event")
*/
protected $participants;
public function __construct()
{
$this->participants = new ArrayCollection();
}
}
因此,您需要做的就是添加一个查询方法(到Event
实体),该方法将使用 Doctrine 集合的过滤功能
/**
* Retrieves all associated participants that are visible
*
* @return DoctrineCommonCollectionsArrayCollection
*/
public function getVisibleParticipants()
{
return $this->participants->filter( function( Participant $participant )
{
// Add only visible participants to the returned collection
return (boolean) $participant->getVisible();
});
}