如何从与ManyToMany相关的表的实体中仅选择一些字段

时间:2015-09-27 02:53:24

标签: symfony doctrine-orm many-to-many

我有两个实体:BlogPost和Category。 BlogPost实体与实体类别具有ManyToMany单向关系。我在BlogPost存储库中编写了一个函数,只获取BlogPost实体的一些字段和Category实体的所有字段。就是这样:

private function getLitePosts(){
    $q = $this->_em->createQuery(
        'select p.id as pid, p.updateDate, p.postTitle, c from ESGISGabonPostBundle:CorporatePost p left join p.categories c'
    );
    return $q->getResult();
}

当它运行时我收到错误:

"message": "[Semantical Error] line 0, col -1 near 'select p.id,': Error: Cannot select entity through identification variables without choosing at least one root entity alias."

我不知道如何处理它。我除了得到这样的东西(用json表示):

[
    {
        "pid": 1,
        "updateDate": 2015-09-26T00:00:00+0100,
        "postTitle": "This is a test",
        "categories": [
            {
                "id": 1,
                "title": "Uncathegorized"
            }
        ]
    },
    {
        "pid": 1,
        "updateDate": 2015-09-26T00:00:00+0100,
        "postTitle": "This is a test 2",
        "categories": [
            {
                "id": 1,
                "title": "Uncathegorized"
            }
        ]
    }
]
是的,有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

我终于找到了解决方案:

$query = $this->createQueryBuilder('p')
        ->select('partial p.{id, updateDate, postTitle}')
        ->leftJoin('p.categories', 'c')
        ->addSelect('partial c.{id}')
        ->getQuery();

return $query->getArrayResult();

它的工作方式与我想要的一样。谢谢TomášVotruba的回答。

答案 1 :(得分:0)

我建议使用查询构建器来完成这个简单的操作。

$query = $this->createQueryBuilder('p')
    ->select('p.id as pid, p.updateDate, p.postTitle, c')
    ->leftJoin('p.categories', 'c')
    ->getQuery();

return $query->getResult();

更多灵感can be found in this answer