【问题标题】:Symfony3 doctrine orm find methodSymfony3学说orm查找方法
【发布时间】:2016-07-29 15:38:56
【问题描述】:

我正在使用 Doctrine ORM 编写一个 Symfony3 应用程序。

所以我要做的是查找给定的电子邮件地址是否存在于表中(每封电子邮件都是唯一的)。所以我有一个带有一些属性的用户存储库,我可以轻松地将数据保存到数据库,但无法检索数据。

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

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

我知道传递给函数的 var 包含一个电子邮件字符串,但我得到的回报是错误,当我在 if 语句之前 var_dump $user 时我得到空值。

我关注了 Symfony docs

【问题讨论】:

    标签: php doctrine-orm symfony


    【解决方案1】:

    您的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();
    

    顺便说一句:如果您要为提交的表单验证这一点,则有一个约束会为您执行此检查:UniqueEntity

    【讨论】:

    • 好吧,可能是这样,因为 ID 是主键,但 findOneByEmail 不是有效的 getDoctrine 方法...?
    • 实际的方法不存在,但教义通过实体存储库上的magic __call method 捕获它并将其转换为通过电子邮件选择。
    • 我现在试一试,但只是感觉必须有一个更简单的解决方案来解决这个问题
    • 更多文档和替代方案:doctrine2.readthedocs.io/en/latest/reference/…
    • @Tomazi,这是超出教义框的,它是一个教义存储库的功能。
    【解决方案2】:

    我认为问题是因为你忘记打电话给getManager()

    所以代码是:

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

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 2016-08-25
      • 1970-01-01
      • 2014-02-06
      相关资源
      最近更新 更多