【问题标题】:Show multiple data from an Entity显示来自实体的多个数据
【发布时间】:2019-03-26 12:29:53
【问题描述】:

我想展示我拥有的每款不同游戏的最佳 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 中获取数据。如何显示每场比赛的数据?

【问题讨论】:

    标签: symfony doctrine twig


    【解决方案1】:

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

    这是你的问题。这总是覆盖。你想做这样的事情:

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

    这应该可以解决您的问题

    【讨论】:

    • 嗨,几乎成功了。我得到键“0、1、2、3、4”不存在的数组的“键”分数。”。我想我现在必须在正确的“记录”索引中循环。像这样:{% for r in records[0] %}。但是如何将 0 替换为游戏的 indexloop 呢?
    • 您应该能够执行 {% for r in records[loop.index] %} 这应该为您提供游戏循环的索引。我不知道 loop.index 在下一个循环中的含义。但这应该可以满足您的需求。
    • 是的,我试过了,但它给了我一个错误:在模板的呈现过程中抛出了一个异常(“注意:未定义的索引:循环”)。
    • 我设法在游戏循环中使用 index.loop 设置了一个属性:{% set i = loop.index0 %} 然后在我的第二个循环中使用它:{% for r in records[我] %}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多