Home > OS >  How to merge duplicates
How to merge duplicates

Time:05-23

I want to merge the same records to:

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

etc.

But now it looks like that

Here is my repository code:

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();
}

twig:

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

controller:

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

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

Can you give me some tips how to get it to work properly?

CodePudding user response:

First change repository code from 'sql' to querybuilder:

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

And then make some Twig changes:

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

CodePudding user response:

As mentioned in the comments, you need to restructure the resulting data array, that is, prepare the desired data structure and pass the template to twig.

Controller method:

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,
    ]);
}

Twig:

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