本文介绍了获取symfony原则findAll以返回具有特定键类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种优雅的方法来重构带有特定键的Symfony findAll返回的数组。例如,如果我有一个实体Animal,字段ID,名称,颜色等,则我想创建一个存储库方法,该方法返回一个包含所有动物的数组,每个动物的键都作为名称字段,这样我就可以进行查找在这个数组中。我现在的操作方式是迭代数组并创建一个新数组,但是我想知道是否可以使用某些现成的东西?

I'm looking for elegant way to restructure the array returned by Symfony findAll with specific keys. For instance If I have an entity Animal with fields id, name, color etc. I would like to make a repository method that returns an array with all animals and the key for each one to be the 'name' field so I can make lookups in this array. The way I'm doing it now is by iterating the array and creating a new one, but I'm wondering if there is something ready made that I can use?

推荐答案

不存在一种内置的教义,即所谓的索引依据,我也很久不知道了。检查代码示例:)。

No there is a thing built-in doctrine, which is called index by, I also didn't know that for long time. Check code examples :).

通过使用getAllLocationsAssoc函数,它将返回由location.id索引的关联数组。因此,数组的键将是db中对象的ID。 您可以像在createQueryBuilder函数中的第二个参数一样使用它。

By using function getAllLocationsAssoc, it will return associative array indexed by location.id. So the keys of array will be the id's of objects in db. You can use it like second parameter in createQueryBuilder function.

class LocationRepository extends EntityRepository
{
    /**
     * @return array
     */
    public function getAllLocationsAssoc(): array
    {
        return $this->createQueryBuilder('location', 'location.id') 
            ->getQuery()
            ->getArrayResult();
    }

}

另一种选择是

<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
/**
 * Class CityRepository
 * @package AppBundle\Repository
 */
class CityRepository extends EntityRepository
{
    /**
     * @return array
     */
    public function getAllCitiesAssoc(): array
    {
        return $this->_em->createQueryBuilder()
            ->select('c')
            ->from('AppBundle:City', 'c', 'c.name') // Third parameter is index-by
            ->getQuery()
            ->getResult();
    }
}

这篇关于获取symfony原则findAll以返回具有特定键类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:37