嵌套的“ for loop”打印所有对象而不是相关对象

时间:2019-05-13 22:32:44

标签: doctrine-orm twig symfony4

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

我在理解下一步要解决的问题时需要一些投入,以找出我需要采取何种方式才能取得理想的结果。

我的知识有限,我一直在学习Symfony 4的KNPU课程>教义,诚然,我略过了Relations教程的一些部分,但“获取关系”的情况与我自己的情况不同,该教程仅获取1 {slug}定义的对象,以后会为我提供帮助。

我的意图

我试图提取所有我的Category实体,并将名称循环为html Header,然后在该循​​环内要运行另一个循环以列出与该类别关联的主题。 供参考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>

我的问题

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

假设, 因为即时通讯要求所有类别对象,所以我引用类别来细化其传递的所有类别ID的主题,因此返回所有主题。

整个Controller不在这里,但我已经包含了功能片段

     /**
     * @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。

说到底,我如何使“主题”循环仅为其嵌套的类别拉正确的主题?自定义查询(如果是,怎么做,我的尝试失败了),一个细枝扩展过滤器?还是我没有想到的任何方法?

关于克服这一障碍的任何建议将不胜感激 如果我错过了任何事情,请告诉我

编辑:

我的实体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;

1 个答案:

答案 0 :(得分:0)

假设您已经将吸气剂和吸气剂添加到实体中,则应该可以在树枝模板中使用它们:

<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>

此外,您实际上并不需要在控制器中返回Topic对象:

 /**
 * @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
    ]);
}

this可能会为您提供更多帮助

相关问题