返回具有特定键的关联数组,用于 findBy 学说存储库函数

eat*_*nts 2 php arrays symfony doctrine-orm

我想要这个功能

$entityManager
->getRepository('AppBundle:Example')
->findBy(array('id' => $id, 'active' => true));
Run Code Online (Sandbox Code Playgroud)

返回以ID 作为键的示例对象的关联数组。例如:

array(
    '100' => 'Example object 1',
    '135' => 'Example object 2'
)
Run Code Online (Sandbox Code Playgroud)

我可以foreach在检索数据后使用来实现此目的,但我想知道是否有正确的方法来执行此操作。

Tho*_*uer 5

您需要在Repository中设置一个自定义方法,然后可以将第二个参数传递给createQueryBuilder(),如下所示:

public function findActiveObjectsIndexedById(): array
{
    return $this->createQueryBuilder('o', 'o.id') 
        // ...
        ->getQuery()
        ->getArrayResult();
}
Run Code Online (Sandbox Code Playgroud)

我刚刚从/sf/answers/3618243121/了解到这一点,找不到比https://www.doctrine-project.org/api/orm/latest/Doctrine/ORM/QueryBuilder更好的文档.html#method_indexBy