嵌套的“for 循环”打印所有 objects 而不是相关的 objects

Nested `for loop` printing all objects rather than related objects

我目前正在使用 Symfony 4 和 Doctrine 开发一个论坛。

我在理解下一步该做什么时遇到问题,需要一些输入以找出我需要采取何种方式才能获得预期的结果。

我的知识有限,我一直在学习 Symfony 4 > Doctrine 的 KNPU 课程,诚然,我浏览了关系教程的几个部分,但 'fetching relations' 场景与我自己的场景不同,教程只获取 {slug} 定义的 1 object,这对我以后有帮助。

我的意图

我正在尝试提取我的所有类别实体并将名称循环为 html Headers,然后在该循​​环中想要 运行 另一个循环以列出与之关联的主题类别。 供参考 core.html.twig 包含我的循环的模板(包含在我的基本模板中,因此可以被覆盖)

<div>
    <div id="forum head">
        <div id="category">
        {% for category in categories %}
            <h4>{{ category.name }}</h4>
            {% for topic in topics %}
                <h6>{{ topic.name }}</h6>
            {% endfor %}
        {% endfor %}
        </div>
    </div>
</div>

我的问题

我如何在控制器中构建我的主题数组,无论关联如何,我总是得到所有主题。

假设, 因为我要求所有类别 Objects 然后我引用类别来优化主题,它传递所有类别 ID,因此返回所有主题。

这里没有完整的控制器,但我包含了函数片段

     /**
     * @Route("/forum", name="page_forum")
     */
    public function index(CategoryRepository $repository, TopicRepository $topicRepository)
    {
        $category = $repository->findBy([],['placement' => 'ASC']);
        $topic = $topicRepository->findBy(['category' => $category],['placement' => 'ASC']);

        return $this->render('forum/index.html.twig', [
            'categories' => $category,
            'topics' => $topic
        ]);
    }

在我的分析器中,我看到执行 SQL 以获取我的主题

SELECT t0.id AS id_1, 
t0.name AS name_2, 
t0.placement AS placement_3,
t0.created_at AS created_at_4, 
t0.updated_at AS updated_at_5,
t0.category_id AS category_id_6 
FROM topic t0 
WHERE t0.category_id IN (?) ORDER BY t0.placement ASC
Parameters:
[▼
  [▼
    41
    42
    43
    44
    45
  ]
]

这证明该主题使用了所有类别 ID。

问题来了,我如何让我的 'topics' 循环只为它嵌套的类别提取正确的主题?自定义查询(如果是这样,我的尝试失败了),一个树枝扩展过滤器?或者我没有想到的任何方法?

如有任何关于克服此障碍的建议,我们将不胜感激 如果我错过了什么让我知道

编辑:

我的实体 CategoryTopic 相关如下(看到一个类似的问题包括这些并意识到它相当无能)

类别

     /**
     * @ORM\OneToMany(targetEntity="App\Entity\Topic", mappedBy="category")
     */
    private $topics;

话题

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="topics")
     * @ORM\JoinColumn(nullable=false)
     */
    private $category;

假设您已经将 getter 和 setter 添加到您的实体中,您应该能够在您的 twig 模板中使用它们:

<div id="forum head">
    <div id="category">
    {% for category in categories %}
        <h4>{{ category.name }}</h4>
        {% for topic in category.getTopics() %}
            <h6>{{ topic.name }}</h6>
        {% endfor %}
    {% endfor %}
    </div>
</div>

此外,您实际上并不需要 return 控制器中的主题对象:

 /**
 * @Route("/forum", name="page_forum")
 */
public function index(CategoryRepository $repository, TopicRepository $topicRepository)
{
    $category = $repository->findBy([],['placement' => 'ASC']);
    //$topic = $topicRepository->findBy(['category' => $category],['placement' => 'ASC']);

    return $this->render('forum/index.html.twig', [
        'categories' => $category,
        //'topics' => $topic
    ]);
}

或许能帮到你更多