如何合并重复项

How to merge duplicates

我想将相同的记录合并到:

Audi A3 / S3 / RS3
   8V / 8Y
Audi A4 / S4 / RS4
   B8 / B9

等等

But now it looks like that

这是我的存储库代码:

public function cars(): array
{
    $conn = $this->getEntityManager()->getConnection();

    $sql = 'select car.name as car, model.name as model from car join model on car.id = model.car_id';

    $stmt = $conn->prepare($sql);
    // returns an array of arrays (i.e. a raw data set)
    return $stmt->executeQuery()->fetchAllAssociative();
}

树枝:

{% for car in cars %}
{{ car.car }}
{{ car.model }}
{% endfor %}

控制器:

public function index(ModelRepository $modelRepository): Response
{
   $cars = $modelRepository->cars();

    return $this->render('index/index.html.twig', [
        'cars' => $cars,
    ]);
}

你能给我一些如何让它正常工作的提示吗?

如评论中所述,您需要重构结果数据数组,即准备所需的数据结构并将模板传递给twig。

控制器方法:

public function index(ModelRepository $modelRepository): Response
{ 
    $cars = [];
    foreach ($modelRepository->cars() as $item) {
        $cars[$item['car']][] = $item;
    } 
    return $this->render('index/index.html.twig', [
        'cars' => $cars,
    ]);
}

树枝:

{% for key, car in cars %}
    {{ key }}
    {% for item in car %}
        {{ item.model }}
    {% endfor %}
{% endfor %}

首先将存储库代码从 'sql' 更改为 querybuilder:

public function cars()
{
    return $this->createQueryBuilder('m')
        ->leftJoin('m.model', 'model')
        ->addSelect('model')
        ->addOrderBy('model.car', 'asc')
        ->getQuery()
        ->getResult()
        ;
}

然后对 Twig 进行一些更改:

{% for car in cars %}
  {{ car.name }}
    {% for model in car.model %}
      {{ model.name }}
    {% endfor %}
{% endfor %}