如何在 Doctrine 2 中获取类而不是数组

2022-01-03 00:00:00 php doctrine doctrine-orm doctrine-query

我可以使用这种结构从数据库中获取我的数据:

I am able to fetch my data from database by using this structure:

$user = $this->getDoctrine()
->getRepository('AcmeDemoBundle:Emails')
->find(8081);

当我这样做时,我能够像这样获取我的数据:

When I do that, I am able to get my data like this:

$user->getColumnNameHere();

基本上我可以使用 Entity 类.

Basically I am able to use Entity Class.

但是如果我想使用 QueryBuilder 而不是 find 我只会得到关联数组.

But if I want to use QueryBuilder instead of find I am only getting associative arrays.

$product->createQueryBuilder('p')
        ->setMaxResults(1)
        ->where('p.idx = :idx')
        ->select('p.columnNameHere')
        ->setParameter('idx', 8081)
        ->orderBy('p.idx', 'DESC')
        ->getQuery();
        $product = $query->getResult();

$product 作为数组返回.是否可以使用j Entity Managaer Class来获取它?如果是,如何?

$product returnds as array. Is it possible to fetch it withj Entity Managaer Class? If yes, how?

我挖掘了文档,但文档中似乎不可能或不存在,或者我只是瞎了:)

I digg the documentation but it seems not possible or not exist in the doc or I'm just blind :)

推荐答案

可以,通常使用:

$repository
    ->createQueryBuilder('p')
    ->getQuery()
    ->execute()
;

这应该会返回一个实体数组.

This should return you an array of entities.

如果您想获得单个实体结果,请使用 getSingleResultgetOneOrNullResult:

If you want to get a single entity result, use either getSingleResult or getOneOrNullResult:

$repository
    ->createQueryBuilder('p')
    ->getQuery()
    ->getOneOrNullResult()
;

警告:这些方法可能会抛出NonUniqueResultException.

Warning: These method can potentially throw NonUniqueResultException.

好的,所以问题是关于部分对象的:http://docs.doctrine-project.org/en/latest/reference/partial-objects.html

Ok, so the question was about partial objects: http://docs.doctrine-project.org/en/latest/reference/partial-objects.html

相关文章