2016-07-29 92 views
1

我正在使用Doctrine ORM編寫Symfony3應用程序。Symfony3 doctrine orm查找方法

所以我想要做的是找到一個給定的電子郵件地址是否存在一張表(每封電子郵件是唯一的)。所以我有一個用戶存儲庫的一些屬性,我可以很容易地堅持數據到數據庫但未能檢索數據。

/** 
* @param $email 
*/ 
public function findUserByEmail($email) 
{ 
    $user = $this->getDoctrine() 
     ->getRepository('TestBundle:TestUser') 
     ->find($email); 

    if (!$user) { 
     echo 'Error';die(); 
    } 
} 

我知道傳遞給函數的變種中包含電子郵件字符串,但我所得到的回報是錯誤,當我的,如果statment之前的var_dump $用戶我得到空。

我跟着Symfony的docs

回答

2

User可能有一個單獨的主鍵字段。只有通過主鍵才能檢索到repo上的find()方法。

Repositories use __call to dynamically process findBy* and findOneBy* methods,所以你可以這樣調用它:

$repo = $this->getDoctrine()->getRepository('TestBundle:TestUser'); 

// magic find method 
$user = $repo->findOneByEmail($email); 

// explicit find method 
$user = $repo->findOneBy(['email' => $email]); 

// custom QueryBuilder 
$user = $repo->createQueryBuilder('user') 
    ->where('user.email = :email') 
    ->setParameter('email', $email) 
    ->getQuery() 
    ->getSingleResult(); 

BTW:如果您要驗證這對於提交的表單,有一個contraint做這個檢查你:UniqueEntity

+0

好的可能是這樣的,因爲ID是主鍵,但findOneByEmail不是一個有效的getDoctrine方法...? – John

+0

實際的方法不存在,但教義通過[魔法__call'方法](http://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods)捕獲它。在實體的存儲庫上,並將其轉換爲通過電子郵件進行選擇。 – NDM

+0

我現在就試試這個,但是有一種感覺,必須有一個更簡單的解決方案才能從Doctrinebox中獲得更多的東西 – John

0

我認爲這個問題是因爲你忘記了撥打getManager()

因此,代碼是:

$em = $this->getDoctrine()->getManager(); 
$user = $em->getRepository('TestBundle:TestUser')->findOneBy(['email' => $email]); 

希望它會幫助你!