1

我正在尝试将从表单输入的电子邮件地址与数据库中已有的电子邮件地址进行比较,我认为最好的方法是使用 findByEmail 方法。

我希望在表中找到特定条目的电子邮件地址,但它会返回整个条目(名字、姓氏等等……)。如何仅在表格中找到条目的电子邮件地址?

我知道我可以使用 aforeach来遍历条目,但我认为这有点违背了使用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
4

1 回答 1

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 而不是 findBy,那么您将直接获取对象而不是在集合中。

或者,如果您必须仅获取电子邮件地址进行比较。

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

请注意,您可以在我的第一个示例中使用 $person->getEmail() 来获得相同的结果。

于 2016-12-14T20:58:22.443 回答