显示来自实体的多个数据

时间:2019-03-26 12:29:53

标签: symfony doctrine twig

我想显示我拥有的每个不同游戏的最佳5分。所以我做了这个功能:

public function records (){
    $em = $this->getDoctrine()->getManager();
    $games = $em->getRepository(Game::class)->findAll();

    foreach($games as $g){
        $records = new ArrayCollection;
        $records = $em->getRepository(Game::class)->findAllRecords($g->getId());
    }


    return $this->render('game/records.html.twig', [            
        'games' => $games,
        'records' => $records,
    ]);
}

这是存储库功能:

public function findAllRecords($id){
    $qb = $this->createQueryBuilder('g');

    $qb->select('g.name')
        ->innerJoin('g.Parties', 'p')
        ->innerJoin('p.playeds', 'y')
        ->innerJoin('y.joueur', 'j')
        ->addSelect('y.score')        
        ->addSelect('j.nom, j.prenom')
        ->where('g.id = :id')
        ->setParameter('id', $id)            
        ->orderBy('y.score', 'DESC')
        ->setMaxResults('5');
    var_dump($qb->getDQL());
    $query = $qb->getQuery();
    return $query->getResult();
}

最后是视图:

{% for g in games %}
{{ g.name }}
<table class="table">
    <tbody>
        <tr>                
            <th>score</th>
        </tr>
            {% for r in records %}
       <tr>
            <td>{{ r.score }}</td>
        </tr>
            {% endfor %}
    </tbody>
</table>
{% endfor %}

它不能完全正常工作,因为我只是从上一个游戏ID中获取数据。如何显示每个游戏的数据?

1 个答案:

答案 0 :(得分:2)

foreach($games as $g){ $records = new ArrayCollection; $records = $em->getRepository(Game::class)->findAllRecords($g->getId()); }

这是您的问题。这总是覆盖。您想做类似的事情:

$records = new ArrayCollection;
foreach($games as $g) {
  $records[] = $em->......;
}

那应该可以解决您的问题