Doctrine2自我参考查询 - 不起作用

时间:2013-10-02 02:44:28

标签: doctrine-orm

$我正在尝试使用doctrine 2查询构建器

创建以下方案
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致命错误:   未捕获的异常'Doctrine \ ORM \ Query \ QueryException'   消息'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   追踪:\ 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):   教义\ ORM \查询\ Parser-&GT; semanticalError('级   实体\埃德...')\ n#2   /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(1561):   教义\ ORM \查询\ Parser-&GT; JoinAssociationPathExpression()\ N#3   /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(1506):   教义\ ORM \查询\ Parser-&GT; JoinAssociationDeclaration()\ N#4   /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/Parser.php(1435):   教义\ ORM \查询\ Parser-&GT;加入()\ N#5   / var / www / pcb_frame_work / System / Librari in   /var/www/pcb_frame_work/System/Libraries/Vendors/Doctrine/ORM/Query/QueryException.php   在第49行,引用者:

1 个答案:

答案 0 :(得分:1)

我不知道我是否完全理解你,但我认为你必须将你的ManyToOne关系更改为:

/**
 * @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