【问题标题】:Key "productTitle" for array with keys "0, catTitle" does not exist in EagleShopBundle:global:product.html.twigEagleShopBundle:global:product.html.twig 中不存在键为“0,catTitle”的数组的键“productTitle”
【发布时间】:2016-01-28 08:17:13
【问题描述】:

我正在尝试加入两个表并在 twig 模板中打印一个值,但我遇到了这个问题。

这是我的控制器操作。

/**
     * @Route("products/display/{id}")
     * @Template()
     */
    public function displayAction($id) {

        $em = $this->container->get('doctrine.orm.entity_manager');
        $qb = $em->createQueryBuilder();

        $qb->select('p, pc.catTitle')
                ->from('EagleShopBundle:Products', 'p')
                ->leftJoin('EagleShopBundle:ProductCategory', 'pc', \Doctrine\ORM\Query\Expr\Join::WITH, 'pc.id = p.category')
                ->where($qb->expr()->eq('p.id', '?5'))
                ->setParameter(5, $id);

        $product = $qb->getQuery()->getOneOrNullResult();

        return $this->render("EagleShopBundle:global:product.html.twig", array(
                    'product' => $product,
                    'image_path' => '/bundles/eagleshop/images/'
        ));
    }

这是我与问题相关的树枝文件行,

<h1>{{product.productTitle}}</h1>

我猜问题与这条线有关

$qb->select('p, pc.catTitle')

这是我得到的错误,

键为“0,catTitle”的数组的键“productTitle”不存在 EagleShopBundle:global:product.html.twig

【问题讨论】:

  • 这两个实体之间有关系吗?也许你可以在这里粘贴Products实体代码?
  • 是的,当我尝试 $qb->select('p.productTitle, pc.catTitle') 时,它可以工作。但我也需要其他文件...
  • 好的,给我几分钟 - 我正在写答案

标签: symfony doctrine twig


【解决方案1】:

您可以尝试下一个查询:

$qb->select('p, partial pc.{id, catTitle}') 
                // if you need full productCategory object then write just 'p, pc'
            ->from('EagleShopBundle:Products', 'p')
            ->leftJoin('p.category', 'pc') 
               //productCategory is the field 
               //in product entity which has relation to product category entity, 
               //paste your field (not column!) name here 
               //if it is not productCategory
            ->where('p.id = :productId')
            ->setParameter('productId', $id);

附言
最好将查询移动到实体存储库:)
附言
Doctrine partial objects
UPD
固定查询 - 使用正确的字段名称

【讨论】:

  • 很抱歉,我遇到了这个问题,[Semantical Error] line 0, col 96 near 'pc WHERE p.id': Error: Class Eagle\ShopBundle\Entity\Products没有名为 productCategory 的关联
  • 你说你有实体之间的关系。那么,您能否粘贴Products 实体代码 - 我只需要字段定义+它们的注释。
  • 哦,我明白了,正如我在回答中所说,如果您在与ProductCategory 实体相关的Product 实体中的字段名称不是productCategory,您必须写下您自己的名字。正如我现在所看到的 - 你在你的问题中说你的字段名称是category。将编辑我的答案。
  • Still 'Method "catTitle" for object "Eagle\ShopBundle\Entity\Products" 在 EagleShopBundle:global:product.html.twig 中不存在这个问题真的很抱歉我完全陌生这个部分对象的概念。
  • 由于对象是相关的,并且您在查询中彼此连接,这与 sql 不同 - 结果字段将处于同一级别。对于教义,如果你把一个人加入另一个人,你必须像通过某种关系树一样。在你的情况下,我认为对于 catTitle,它会是这样的:{{ product.category.catTitle }}
猜你喜欢
  • 1970-01-01
  • 2016-06-14
  • 2023-03-23
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多