什么是使用findBy'Field方法的正确方法?

问题描述:

我想比较一个从表单输入的电子邮件地址与数据库中已存在的电子邮件地址,我认为最好的方法是使用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

如果成功获取了实体通过电子邮件,则电子邮件必须匹配。

$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