错误:无效的PathExpression。必须是SingleValuedAssociationField。在Doctrine2中

时间:2015-10-20 15:38:29

标签: symfony doctrine-orm

我曾经在下面

$qb = $this->createQueryBuilder('cat');
        $result = $qb
            ->select('IDENTITY(c.name) AS catname')
            ->leftJoin("CatalogueBundle:Product", 'p',
                Join::WITH,
                'cat.product = p.id')
            ->leftJoin("CatalogueBundle:Category", 'c',
                Join::WITH,
                'cat.category = c.id')
            ->where('p.id =:product')
            ->setParameter('product',$productId)
            ->getQuery()
            ->getResult();
        return $result;

从symfony2中的两个查询中获取数据,但它给出了以下错误

[Semantical Error] line 0, col 18 near 'name) AS catname': Error: Invalid PathExpression. Must be a SingleValuedAssociationField. 

CatalogueBundle:Category实体中有一个字段名称。无法找到原因?

1 个答案:

答案 0 :(得分:3)

IDENTITY函数仅在您希望将关联用作简单字段时才有用,以避免无用连接(由于DQL语法)。

在您的情况下,c.name不是关联,因此IDENTITY调用无效。只需写下:

$qb = $this->createQueryBuilder('cat');
$result = $qb
    ->select('c.name AS catname')
    ->leftJoin("CatalogueBundle:Product", 'p',
        Join::WITH,
        'cat.product = p.id')
    ->leftJoin("CatalogueBundle:Category", 'c',
        Join::WITH,
        'cat.category = c.id')
    ->where('p.id =:product')
    ->setParameter('product', $productId)
    ->getQuery()
    ->getResult();
return $result;

顺便说一句,如果我正确理解你的模型,查询可以简化为:

$qb = $this->createQueryBuilder('cat');
$result = $qb
    ->select('c.name AS catname')
    ->innerJoin('cat.category', 'c') // left is useless, you get null c.name
    ->where('IDENTITY(cat.product) = :product')
    ->setParameter('product', $productId)
    ->getQuery()
    ->getResult();
return $result;