可以将groupBy列用作具有Doctrine查询构建器的分组集合的关联数组索引吗?

时间:2017-09-07 10:16:26

标签: symfony doctrine-orm doctrine doctrine-query

给定如下表格结构:

Matches:
| id | round | home_team | away_team |
|  1 |   1   | Juventus  |  Milan    |
|  2 |   1   | Inter     |  Roma     |
|  3 |   2   | Juventus  |  Inter    |
|  4 |   2   | Roma      |  Milan    |

...是否可以根据其中一列构建集合? 我希望根据matches列在收藏中整理所有round

我当前的查询构建器如下所示:

/** @var MatchRepository $matchRepository */
$matchRepository = $em->getRepository('JCNApiBundle:Football\Match');

return $matchRepository->createQueryBuilder('m', 'm.round')
    ->where('m.competition = :competition')
    ->setParameter('competition', $competitionId)
    ->groupBy('m.id, m.round')
    ->getQuery()
    ->getArrayResult()
;

不幸的是,每组只返回一行:(每match一个round

[
    // Round 1
    1 => [
        // Match 1
        "id" => 1,
        "round" => 1,
        "home_team" => "Juventus",
        "away_team" => "Milan",
    ],
    // Round 2
    2 => [
        // Match 3
        "id" => 3,
        "round" => 2,
        "home_team" => "Juventus",
        "away_team" => "Inter",
    ]
]

我正在寻找类似的东西:

[
    // Round 1
    1 => [
        // Match 1
        0 => [
            "id" => 1
            "round" => 1
            "home_team" => "Juventus"
            "away_team" => "Milan"
        ],
        // Match 2
        1 => [
            "id" => 2
            "round" => 1
            "home_team" => "Inter"
            "away_team" => "Roma"
        ]
    ]
    // Round 2
    2 => [
        // Match 3
        0 => [
            "id" => 3
            "round" => 2
            "home_team" => "Juventus"
            "away_team" => "Inter"
        ],
        // Match 4
        1 => [
            "id" => 4
            "round" => 2
            "home_team" => "Roma"
            "away_team" => "Milan"
        ]
    ]
]

这可以通过Doctrine查询构建器实现吗?

2 个答案:

答案 0 :(得分:1)

不,这根本不可能与SQL一起使用。 SQL查询始终返回二维数组。你想得到一个三维的。

您需要跳过GROUP BY部分并迭代返回的集合以在PHP中创建所需的结构。

答案 1 :(得分:1)

正如Jakub Matczak所说,使用SQL是不可能的。

但是,如果您希望查询返回此类多维数组,则可以write a custom hydrator。在水槽内部通过手动“圆”进行分组。 因此,Doctrine允许您在单独的类中分离这个水合/分组逻辑,但您仍然需要对其进行编码。