2013-10-02 63 views
0

$我試圖教義2查詢生成器創建以下情形Doctrine2自我參照查詢 - 不工作

SELECT 
    p . * 
FROM 
    _tree p 
    LEFT JOIN 
    _tree c ON p.id = c.parent_id 
     AND (c.lft >= p.lft AND c.rgt <= p.rgt) 
WHERE 
    p.id = 3 

我已成立由Doctrine2

 
    class Tree { 

    /** 
    * @var \Tree 
    * 
    * @ORM\ManyToOne(targetEntity="Tree") 
    * @ORM\JoinColumns({ 
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") 
    * }) 
    */ 
    private $parent; 

     // other code 
    } 

這裏生成以下關係自我是我的回購類

 
_em->createQueryBuilder(); 
     $qb->select('p') 
      ->from('Entity\Tree', 'p') 
      ->leftJoin('p.Entity\Tree','c', 'ON','p.id = c.parent_id'); 

     return $qb->getQuery()->getResult(); 
    } 
} 

,但我無法完成它。它拋出以下錯誤

[Tue Oct 01 22:30:11 2013] [error] [client 127.0.0.1] PHP Fatal error: Uncaught exception 
'Doctrine\\ORM\\Query\\QueryException' with message 'SELECT p FROM Entity\\Tree p LEFT JOIN p.Entity\\Tree c ON p.id = c.parent_id' in 
/var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/QueryException.php:39\nStack trace:\n#0 
/var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(429): 
Doctrine\\ORM\\Query\\QueryException::dqlError('SELECT p FROM E...')\n#1 /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(925): 
Doctrine\\ORM\\Query\\Parser->semanticalError('Class Entity\\Ed...')\n#2 /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(1561): 
Doctrine\\ORM\\Query\\Parser->JoinAssociationPathExpression()\n#3 /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(1506): 
Doctrine\\ORM\\Query\\Parser->JoinAssociationDeclaration()\n#4 /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(1435): 
Doctrine\\ORM\\Query\\Parser->Join()\n#5 /var/www/pcb_frame_work/System/Librari in 
/var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/QueryException.php on 
line 49, referer: 
+0

您可以添加樹實體的完整定義?也許這可以清楚地看到你在示例查詢中使用的左列和右列 –

回答

1

我不知道我完全理解你,但我認爲你必須改變你的多對一關係:

/** 
* @var \Tree 
* 
* @ORM\ManyToOne(targetEntity="Tree", inversedBy="children") 
* @ORM\JoinColumns({ 
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id") 
* }) 
*/ 
private $parent; 

/** 
* @ORM\OneToMany(targetEntity="Tree", mappedBy="parent") 
*/ 
private $children; 

這樣,你可以訪問的孩子與$Tree->children和它的父母與$Tree->parent。約自參照協會

更多信息可以在這裏找到:http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#one-to-many-self-referencing