2016-12-14 142 views
1

我想比較一個從表單輸入的電子郵件地址與數據庫中已存在的電子郵件地址,我認爲最好的方法是使用findByEmail方法。什麼是使用findBy'Field方法的正確方法?

我希望找到表中特定條目的電子郵件地址,但它會返回整個條目(名,姓和更多...)。 如何才能找到表格中條目的電子郵件地址?

我知道我可以使用foreach遍歷條目,但我認爲這有點違背了使用findByEmail函數的目的。

這裏是我試過到目前爲止:

$formEmail = $form->get('email')->getData(); 
$personEmail = $em->getRepository('UserBundle:User')->findByEmail($formEmail); //Should just find the email address of a person in the database. 
var_dump($personsEmail); //returns the whole row associated with the email address (first name, last name…..) 
var_dump(if($formEmail == $personEmail));die; //returns false when it should be true because it finds the whole row instead of the email address 
+0

實際上你試圖實現的目標並不明顯:如果找到了一行 - 它將使電子郵件與'$ formEmail'完全相同,因爲您將其用作搜索條件。 – zerkms

+0

在這一行中:'if($ formEmail == $ personEmail)'你正在比較一個文本值和一個行值,這是行不通的! –

+0

@AlvinBunk對不起,我在'foreach'循環中試圖將它遺留下來。 'foreach($ personEmails as $ email){$ personEmail = email-> getEmail(); var_dump($ formEmail == $ personEmail);}' – grgre

回答

0

如果成功獲取了實體通過電子郵件,則電子郵件必須匹配。

$formEmail = $form->get('email')->getData(); 

    $person = $em->getRepository('UserBundle:User')->findOneByEmail($formEmail); 

    if ($person instanceof User) { 

     // you found a user by email, so the email therefore must match ...   
    } 

注意,使用findOneBy not findBy,那麼你將直接獲取對象而不是集合中。

或者,如果你必須只取對比的電子郵件地址。

$email = $em->createQueryBuilder() 
     ->select('u.email') 
     ->from('UserBundle:User', 'u') 
     ->where('u.email = :email') 
     ->setParameter('email', $formEmail) 
     ->getQuery() 
     ->getSingleScalarResult() 
    ; 

請注意,雖然您可以在我的第一個示例中使用$ person-> getEmail()以獲得相同的結果。

+0

findOneBy和findBy返回相同的東西,整個集合 – grgre

+0

請參閱findOneBy的文檔:http://www.doctrine-project.org/api/orm/2.5/source-class-Doctrine.ORM.EntityRepository.html#183-196 - 返回一個實體,而不是一個集合。另見:http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/dql-doctrine-query-language.html#magic-finders - 另請參閱http://docs.doctrine -project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#by-simple-conditions - 如果這不起作用,那麼您的設置可能會有更根本性的錯誤。 – Richard

相關問題