2016-07-29 72 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]); 

希望它会帮助你!

相关问题