2014-01-09 103 views
1

我在Doctrine:User和Club中有2個實體。兩者都包含此文本的權利:Doctrine 2 EM - >從2個實體獲得結果1個表

/** 
* @ORM\ManyToMany(targetEntity="User", mappedBy="sms_followers") 
**/ 
private $smsfollowers; 

另一個目標實體是俱樂部。

我使用findOneBy()來檢索俱樂部的概述。你可以看到俱樂部的所有數據。

現在我想表明有多少SMS追隨者。我應該怎麼做?

回答

0

這應該讓你啓動並運行。我將所有代碼放在控制器中,以便您理解。

<?php 

namespace Acme\YourBundle\Controller; 

use Symfony\Component\DependencyInjection\ContainerAware; 

class YourBundle extends ContainerAware 

    /** 
    * @return EntityManager 
    */ 
    protected function getEntityManager() 
    { 
     return $this->container 
      ->get('doctrine') 
      ->getEntityManager(); 
    } 

    /** 
    * Get the number of followers for a particular class 
    * 
    * @param string The class 
    * @return int The number of followers 
    */ 
    protected function getNumberOfSMSFollowers($class) 
    { 
     $entityManager = $this->container 
      ->get('doctrine') 
      ->getEntityManager(); 

     $queryBuilder = $entityManager 
      ->createQueryBuilder() 
      ->select('count(f.id)') 
     // from the appropriate class 
      ->from($class, 'c') 
      ->innerJoin('c.smsfollowers','f'); 

     return $queryBuilder 
      ->getQuery() 
      ->getSingleScalarResult(); 
    } 

    /** 
    * Get the number of followers in 2 different entities 
    * 
    * @return response The response you wish to give 
    */ 
    public function getNumberOfFollowersAction() 
    { 
     // Your classes 
     $userClass ="Acme\UserBundle\User"; 
     $clubClass ="Acme\ClubBundle\Club"; 

     $nbFollowersInUserClass = $this->getNumberOfSMSFollowers($userClass); 
     echo $nbFollowersInUserClass; 

     $nbFollowersInClubClass = $this->getNumberOfSMSFollowers($userClass); 
     echo $nbFollowersInClubClass; 

     //... 
    } 
}