【问题标题】:Symfony2 - How to fetch/join only related entities with a certain condition (one-to-many relation)?Symfony2 - 如何仅获取/加入具有特定条件(一对多关系)的相关实体?
【发布时间】:2013-10-26 12:49:00
【问题描述】:

我在事件和参与者实体之间存在单对多关系。 在我的控制器中,我可以执行以下操作:

$participants = $event->getParticipant();

但现在我只想要 visible 属性值为 1 的参与者。

我怎样才能得到这些收藏?因为参与者是事件实体中具有participant.event_id = event.id 的所有参与者的数组集合。

【问题讨论】:

    标签: symfony doctrine


    【解决方案1】:

    您可以轻松地在您的 EventRepository 中创建一个仅将可见参与者加入事件的方法:

    // YourBundle/Entity/EventRepository.php
    
    public function getEventFilterVisibleParticipants($event_id)
    {
        return $repository->createQueryBuilder('event')
            ->where('event.id = :event_id')
            ->leftJoin('event.participants', 'participant', 'WITH', 'participant.visible = :visibility')
            ->setParameter('event_id', $event_id)
            ->setParameter('visibility', 1)
            ->orderBy('event.startDate', 'DESC')
            ->getQuery()
            ->getResult()
        ;
    }
    

    ...现在在您的控制器中执行以下操作:

    $event = $this
        ->getDoctrine()
        ->getRepository('YourBundle:Event')
        ->getEventFilterVisibleParticipants($id)
    ;
    
    $participants = $event->getParticipants(); // returns the filtered collection
    

    【讨论】:

    • 它说未定义的方法'getEventWithVisibleParticipants'。方法名称必须以 findBy 或 findOneBy! 开头!
    • 我在发布后的回答中将方法名称从getEventWithVisibleParticipants 更改为getEventFilterVisibleParticipants。确保您从教义中获取正确的存储库并检查方法名称是否匹配:)
    • 但我找到了一个更简单的解决方案 - 我只是在遍历对象时通过其可见性在 twig-template 中对其进行过滤;)
    • 这可能“更容易”,但它限制了只对模板的可见参与者做某事的可能性......而且它BAD就性能而言,因为您正在从数据库中获取实际上不需要的实体。这就是你应该使用存储库方法的原因——这正是存储库提供这些方法的目的。
    猜你喜欢
    • 1970-01-01
    • 2014-05-09
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2011-07-21
    • 2015-12-12
    相关资源
    最近更新 更多