2016-08-23 58 views
1

我有這種方法的存儲庫:symfony的3.1倉庫方法混亂

public function getCountryId($code_2a) 
{ 
    return $this 
     ->createQueryBuilder('e') 
     ->andWhere('e.code2a = :code_2a') 
     ->setParameter('code_2a', $code_2a) 
     ->getQuery() 
     ->execute(); 
} 

,並與該呼叫控制器:

$country = $em->getRepository('AppBundle:Countries')->getCountryId('GB'); 

正如我在$國家明白,我將與實體表中記錄的數據「英國」在這種情況下。

但是,如果在控制器我做的:

$country_id = $country->getId(); 

我得到一個異常:

Error: Call to a member function getId() on array 

這混淆了我。我怎樣才能得到該國的$id

回答

4

您的查詢返回包含對象(一個或多個)陣列,所以如果你希望收到你必須使用getOneOrNullResult

public function getCountryId($code_2a) 
{ 
    return $this 
     ->createQueryBuilder('e') 
     ->andWhere('e.code2a = :code_2a') 
     ->setParameter('code_2a', $code_2a) 
     ->getQuery() 
     ->getOneOrNullResult() 
    ; 
} 
0

在控制器改變您的查詢只有一個對象

$country = $em->getRepository('AppBundle:Countries')->findOneByCode2a('GB'); 
if($country) { 
    $country_id = $country->getId(); 
} 

返回一個對象國家。如果使用findBy,則返回包含對象的數組。

+0

謝謝DOZ。這兩條消息幫助了我。 – Carlos