2015-10-20 76 views
0

我用下面錯誤:PathExpression無效。必須是SingleValuedAssociationField。在Doctrine2

$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實體字段名。不能找到爲什麼會發生?

回答

2

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; 
相關問題