Doctrine 2, query inside entities

前端 未结 5 1565
自闭症患者
自闭症患者 2020-12-13 16:51

How do I perform queries in an entity?

namespace Entities\\Members;

/**
 * @Entity(repositoryClass=\"\\Entities\\Member\\MembersRepository\")
 * @Table(name         


        
5条回答
  •  自闭症患者
    2020-12-13 17:00

    Your ArrayCollection already implements a filter() method, you need to pass a Closure to get it to work your entities (here, the commentEntries).

    $idsToFilter = array(1,2,3,4);
    
    $member->getComments()->filter(
        function($entry) use ($idsToFilter) {
           if (in_array($entry->getId(), $idsToFilter)) {
               return true;
           }
    
           return false;
        }
    ); 
    

    (not tested)

    Note that such method will iterate and eager load over all your Comments, so in case where a User has a lot it may be a big bottleneck;

    In most case, you want to use a custom repositories, where you can place such logic.

    As timdev suggested, you can create a MemberService which will wrap such call by being aware of the EntityManager.

    Separating Entities from the Peristance Layer is a big improvement over Doctrine 1, and you should not break that rule.

提交回复
热议问题