【问题标题】:symfony2 assert inheritancesymfony2 断言继承
【发布时间】:2013-02-28 02:00:12
【问题描述】:

我正在使用 Symfony2。
我有两个课程:employeephysiciandoctoremployee 的子类。

实体employee

@UniqueEntity(fields={"email"}, message="Este valor ya se ha utilizado.")

当我唯一性时,有效的电子邮件字段仅针对员工和医生分别进行验证。

如果我插入 employee3 mail1@mail.com 错误断言 symfony2 工作正常
如果我插入医生2 mail3@mail.com 错误断言 symfony2 工作正常
如果我插入 doctor2 mail1@mail.com 显示错误 sql 但没有错误断言 symfony2。

【问题讨论】:

    标签: validation symfony


    【解决方案1】:

    这是UniqueEntityValidator 类的一部分:

    $repository = $em->getRepository($className);
    $result = $repository->{$constraint->repositoryMethod}($criteria);
    
    /* If the result is a MongoCursor, it must be advanced to the first
     * element. Rewinding should have no ill effect if $result is another
     * iterator implementation.
     */
    if ($result instanceof \Iterator) {
        $result->rewind();
    }
    
    /* If no entity matched the query criteria or a single entity matched,
     * which is the same as the entity being validated, the criteria is
     * unique.
     */
    if (0 === count($result) || (1 === count($result) && $entity === 
        ($result instanceof \Iterator ? $result->current() : current($result)))) {
        return;
    }
    

    如您所见,$em->getRepository($className) 将用作存储库。问题是,如果没有 repositoryMethod 选项,Symfony 将使用 Doctrine 的 findBy 方法,该方法在每个存储库中都可用,甚至是继承自 EntityRepository 的自定义存储库。

    当您的实体是 Employee 时,Symfony 将在员工中寻找具有给定字段的现有实体

    $em->getRepository('AcmeHelloBundle:Employee')->findBy($criteria);
    

    当实体是 Physician 时也会发生同样的情况(只在医生中查看):

    $em->getRepository('AcmeHelloBundle:Physician')->findBy($criteria);
    

    引用你的话:

    如果我插入 employee3 mail1@mail.com 错误断言 symfony2 工作正常

    那是因为没有电子邮件为 mail1@mail.com 的员工

    如果我插入 doctor2 mail3@mail.com 错误断言 symfony2 工作正常

    原因同上。

    如果我插入医生 2 mail1@mail.com 显示错误 sql 但没有错误断言 symfony2

    问题来了!没有mail1@mail.com 邮箱的医生!有一位员工使用相同的电子邮件,但在针对医师存储库使用findBy 时,它返回0

    也许您应该将repositoryMethod 选项设置为存储库方法,该方法在使用数组作为条件进行搜索时会查找employeephysician

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2021-03-09
      • 2015-08-06
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多