12

我有class categroiesclass Products

在我的存储库中,我有功能

getProducts($categoryid,$location)

我需要像这样循环输入树枝模板

 {% for category in categories %}
    --{{ category.name }}--
      {% for product in getProducts(category.id,location) %}
     --{{ product.name }}--
    {% endfor %}
 {% endfor %}

或者有没有更好的方法

4

4 回答 4

20

你不应该。那是业务逻辑,不应出现在模板中。一种解决方案是在控制器和模板调用中创建新操作

{% render '@MyBundle:Product:list' with {category: category.id} %}
于 2012-08-01T07:07:47.343 回答
7

这是一个很老的问题,但我错过了一个像这样的非常简单的解决方案。

可以将 repo 对象传递给 twig 并从 twig 调用 repo 公共方法,如下所示:

在您的控制器中

$oCatRepo = $this->getDoctrine()->getManager()->getRepository('AppBundle:Categories');
....
return $this->render('product_list.html.twig', array('oCatRepo' => $oCatRepo));

然后在你的树枝模板中:

{{ oCatRepo.getProducts(category.id, location) }}

我说这是可能的,许多人会争辩说模板应该只显示数据并让控制器收集数据。我个人不介意让我的模板自己获取数据。

于 2015-04-20T18:25:23.357 回答
1

我怀疑您真正需要的只是使用 WITH 表达式的左连接。就像是:

class CategoryManager
{
    public function loadCategoriesProductsForLocation($location)
    {
        $qb = $this->em->->createQueryBuilder();

        $qb->addSelect('category');
        $qb->addSelect('product');

        $qb->from('MyBundleBundle:Category','category');

        $qb->leftJoin('category.products','product', 
            Expr\Join::WITH, $qb->expr()->eq('product.location', $location));

这将为您提供给定位置的所有类别及其各自产品。

于 2012-08-01T14:23:40.130 回答
1

解决方案与现在如何完成相反。Category 实体应该具有一对多的关系。看看http://symfony.com/doc/2.0/book/doctrine.html#entity-relationships-associations

然后,类别实体应该有一个名为“产品”的 EntityCollection 属性。在您的模板中,您可以通过以下方式解决此问题:

{% for category in categories %}
    --{{ category.name }}--
      {% for product in category.products %}
     --{{ product.name }}--
    {% endfor %}
 {% endfor %}
于 2013-01-18T15:51:22.850 回答