php - 为 findBy 学说存储库函数返回具有特定键的关联数组

标签 php arrays symfony doctrine-orm

我想要这个功能

$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/

相关文章:

php - 在 Underscore 模板中格式化日期

php - 如何在 Symfony 中使用 1 twig 中的 2 种形式?

javascript - 以数组形式发送 Ajax 数据与以手动字符串形式发送不同

php - 多项选择类型,需要数组

symfony - 如何扩展 Sonata\DoctrineORMAdminBundle\Model\ModelManager

php - CakePHP 3 保存 HasOne 关联

php - 简单地尝试更新 mysql 数据库中的项目

php - 为什么我的 PHP 代码不起作用?

c# - 在 C# 中处理 char*(strlen 函数?)

php - 在 Symfony 中访问 wordpress 博客