我曾经在下面
$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
实体中有一个字段名称。无法找到原因?
答案 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;