Doctrine2: Cannot select entity through identification variables without choosing at least one root entity alias

前端 未结 2 743
予麋鹿
予麋鹿 2021-01-18 23:24

I am stuck with an originally very simple doctrine 2 query. I have an entity called Category which has a OneToMany relation with itself (for parent and child categories).

相关标签:
2条回答
  • 2021-01-18 23:43

    Your query is missing some parts. Normal query builder in repo goes like

        $q = $this->getEntityManager()
            ->getRepository('MyBundle:Entity')
            ->createQueryBuilder(‌​'c')
            ->select(‌​'c')
            ->leftjoin(‌​'c.children', 'cc')
            ->addselect(‌​'cc')
            ->where(‌​'c.parent is NULL')
    ....
        return $q;
    
    0 讨论(0)
  • 2021-01-18 23:56

    Your issue is that you are trying to select one field from the Category entity while simultaneously selecting the entire object of the joined Category entity. Unlike plain SQL, with the QueryBuilder component you can't select an entity only from the table you are joining on.

    If you are looking to return your main Category object with the joined children, you can either do ->select(array('c', 'cc')), or simply omit the ->select() call altogether. The former will automatically select the children you need in a single query. The latter will require another SQL query if you want to access children on the main Category entity.

    If there is a reason you want name to select as title in your object, you can always add another function to your entity that is an alias for retrieving the name instead of having to write it in your query:

    function getTitle()
    {
        return $this->getName();
    }
    
    0 讨论(0)
提交回复
热议问题