我想要这个功能
$entityManager
->getRepository('AppBundle:Example')
->findBy(array('id' => $id, 'active' => true));
以 ID 作为键 返回 Example 对象的关联数组。 例如:
array(
'100' => 'Example object 1',
'135' => 'Example object 2'
)
我可以在检索数据后使用 foreach
来实现这一点,但我想知道是否有合适的方法来做到这一点。
最佳答案
您需要在 Repository 中设置自定义方法,然后您可以将第二个参数传递给 createQueryBuilder()
,如下所示:
public function findActiveObjectsIndexedById(): array
{
return $this->createQueryBuilder('o', 'o.id')
// ...
->getQuery()
->getArrayResult();
}
我刚刚从 https://stackoverflow.com/a/51689187/1668200 了解到这个找不到比 https://www.doctrine-project.org/api/orm/latest/Doctrine/ORM/QueryBuilder.html#method_indexBy 更好的文档了
关于php - 为 findBy 学说存储库函数返回具有特定键的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36281237/