【问题标题】:Symfony 3.4 / createQueryBuilder does not work if andWhere() is used (ClassNotFoundException)如果使用 andWhere(),Symfony 3.4 / createQueryBuilder 不起作用(ClassNotFoundException)
【发布时间】:2020-08-01 13:31:46
【问题描述】:

我目前正在尝试构建一个简单的查询来通过用户名查找用户:

namespace Swenso\IntranetBundle\Repository;

use Swenso\IntranetBundle\Entity\Employee;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;

/**
 * @method Employee|null find($id, $lockMode = null, $lockVersion = null)
 * @method Employee|null findOneBy(array $criteria, array $orderBy = null)
 * @method Employee[]    findAll()
 * @method Employee[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class EmployeeRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Employee::class);
    }

    public function findByUsername($value)
    {
        return $this->createQueryBuilder('e')
            ->andWhere('e.username = :val')
            ->setParameter('val', $value)
            ->orderBy('e.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
            ;
    }

运行此代码会导致以下错误:

Attempted to load class "Composite" from namespace "Doctrine\ORM\Query\Expr".
Did you forget a "use" statement for "Symfony\Component\Validator\Constraints\Composite"?

如果我省略了andWhere(),查询运行良好...

如果有人可以帮助我们,那就太好了!

BR wucherpfennig

【问题讨论】:

  • 使用->where() 有效吗? ->andWhere() 表示复合条件。它可以按照您对当前版本的预期工作,但可能并非总是如此。
  • andWhere 可以正常工作。错误消息表明您的实体上有一个未正确定义的复合约束。所以错误实际上来自验证器,而不是查询。你在用表格吗?无论如何,请仔细检查您的复合约束/验证器类,如果找不到问题,可能会发布代码。
  • 对 EasyAdmin 不是很熟悉。复合约束是一个 Symfony 类,它包含多个约束,然后一个接一个地应用它们。大概您在 EasyAdmin 生成的代码中的某处发生了类似的事情。也许搜索 Composite 可能会有所帮助,但也许没有。
  • php 版本?如果可能,请使用 7.4.4。一些早期版本存在一些预加载问题,导致出现神秘错误。当然,清除缓存。单步执行代码可能会有所帮助。只是在这里抓稻草。如果您保留了旧的 composer.lock 文件,那么可以尝试恢复。
  • 您的代码看起来是正确的,您能否验证供应商文件夹 \Doctrine\ORM\Query\Expr\Composite.php 中确实存在该类?也分享你的 composer.json 可能会有所帮助

标签: php symfony doctrine query-builder symfony-3.4


【解决方案1】:

我之前在同一个 symfony 版本上遇到过这个错误,对于这个后查询生成器,我无法执行 ->andWhere(),因为你还没有启动 ->where() 条件语句。

首先总是需要使用 ->where() 来启动条件,然后可以使用更多 ->andWhere()/->orWhere() 连接。

关于原则documentation,他们写了一个注释,我们可以使用 andWhere 而无需设置之前的位置。

还可以尝试查看 symfony 的此文档页面,以检查存储库类是否构建良好 https://symfony.com/doc/3.4/doctrine/repository.html 可能您调用的 etends 服务没有加载好的实体管理器。

我希望这有效。 干杯

【讨论】:

  • 这个答案的第一部分完全是错误的:你总是从 andWhere 开始。总是可以的。试试吧。关于实体管理器的第二部分只是一个纯粹的猜测,除非你能解释错误的实体管理器和“复合”约束错误之间的联系。
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多