How to select only certain fields of the entity with the table related to ManyToMany

advertisements

I have two entities: BlogPost and Category. BlogPost entity has ManyToMany unidirectional relation with entity Category. I wrote a function in BlogPost repository to get only some fields of BlogPost entity and all fields of Category entity. This is it:

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();
}

When it runs I got error:

"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."

I don't know how to deal with it. I excepted to get something like this (represented in 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"
            }
        ]
    }
]

May somebody help me ?


I finally found a solution:

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

return $query->getArrayResult();

It works like I want. Thank you Tomáš Votruba for your answer.