我正在使用 Symfony 6 和 PHP 构建网站。我有 2 个实体:与 ManyToOne 相关的产品和类别(每个类别都有很多产品)。
我想获取所有类别并将每个类别显示为单独的 div 以及该类别的所有产品 inside.So far 我得到了这个
public function index(EntityManagerInterface $entityManager): Response
{
$categories = $entityManager->getRepository(Category::class)->findAll();
return $this->render('index/index.html.twig', [
'categories' => $categories
]);
}
{% for category in categories %}
<div class="category">
<h2>{{ category.name }}</h2>
<ul>
{% for product in category.products %}
<li>{{ product.name }}</li>
{% endfor %}
</ul>
</div>
{% endfor %}
这个循环显示类别和产品,但是 div 是这样复制的:
<div>
<h1>category1</h1>
<p>product1</p>
</div>
<div>
<h1>category1</h1>
<p>product2</p>
</div>
我会喜欢这样的东西:
<div>
<h1>category1</h1>
<p>product1</p>
<p>product2</p>
</div>
我该怎么办?使用 QueryBuilder 进行其他查询?
你应该只改变模板的视图和规则。
public function index(EntityManagerInterface $entityManager): Response
{
$categories = $entityManager->getRepository(Category::class)->findAll();
return $this->render('index/index.html.twig', [
'categories' => $categories
]);
}
<div class="category">
{% for category in categories %}
<h1>{{ category.name }}</h1>
{% for product in category.products %}
<p>{{ product.name }}</p>
{% endfor %}
{% endfor %}
</div>
抱歉,我没有准确描述我想要实现的目标。如果我添加一个产品并且该类别已经存在,我不想创建一个新类别的记录,而只是将这个产品添加到一个现有的同名类别