Search code examples
htmlmysqlsymfonytwiginner-join

How to display information of different table in twig symfony?


I need to display a table, for example 4 columns, I have a Palmares entity with different information.

How to put data from another sql table in the same loop, other information is linked with palmares.categorie.code Here is a part of my template with html.twig

{% for palmares in palmares %}
<tr>
 <td>{{palmares.categorie.code}}</td>
 <td>other information from another table</td>
 <td>{{palmares.compet.date |date("m/d/Y")}}</td>
 <td>{{palmares.compet.lieu}}</td>
</tr>
{% endfor %}

EDIT :

For example I have entity Palmares, Entity Categorie with variable $code integer. If I display palmares.categorie.code in twig it show me integer.

I have an other class OtherInformation with a variable code and it is linked with palmares.categorie.code

My PalmaresRepository have function like :

public function getPalmares(int $id)
    {
        return $this->createQueryBuilder('p')
            ->where('p.saison = :date')
            ->andWhere('p.club = :id')
            ->setParameter('date', date("Y"))
            ->setParameter('id', $id)
            ->getQuery()
            ->getResult();
    }

Solution

  • If the information is linked to your palmares, you can simply join on it to get it simply in TWIG (below a code with query builder but you could as well use DQL if you prefer) :

    /* /src/Repository/PalmaresRepository.php */
    public function getPalmaresWithJoinedEntity()
    {
      $qb = $this
        ->createQueryBuilder('p')
        ->leftJoin('p.joinedField', 'j')
        ->addSelect('j')
      ;
    
      return $qb
        ->getQuery()
        ->getResult()
      ;
    }
    
    /* /templates/your_template.html.twig */
    {# ... #}
    {{ palmares.joinedProperty.someField }}
    

    Note that you are not forced to join in your repository to get your joined data, you can simply alter your template without joining, but you will face the N+1 problem (You will get an additional query per palmares, to get each joined property.)