T
T
Tashiro2013-12-10 10:43:23
symfony
Tashiro, 2013-12-10 10:43:23

How to combine entities by selecting only the required fields and save nesting?

I have a query like:

$qb = $this->createQueryBuilder("p")
        ->addSelect(array("u","c", "cu"))
        ->leftJoin("p.user", "u")
        ->leftJoin("p.comments", "c")
        ->leftJoin("c.user", "cu")
        ->where("p.id = :id");
    $qb->setParameter("id",$id);
    $query = $qb->getQuery();
    return $query->getSingleResult(Query::HYDRATE_ARRAY);

As a result, we have an array of the form:
Array(
  'result' => Array (
        "id" => "111",
        "title" => "no title",
        "user" => Array( "id" => "1", "email" => "1111" )
        "comments" => Array ( "id" => "1", "text" => "aaaa", "user" => Array("id" => "1"));
      )
);

So, if you do as above, then all fields of entities fall into the selection, which is not always correct.
And if you do this:
$qb = $this->createQueryBuilder("p")
        ->addSelect(array("u.id","c", "cu"))
        ->leftJoin("p.user", "u")
        ->leftJoin("p.comments", "c")
        ->leftJoin("c.user", "cu")
        ->where("p.id = :id");
    $qb->setParameter("id",$id);
    $query = $qb->getQuery();
    return $query->getSingleResult(Query::HYDRATE_ARRAY);

The result of the query will be completely different:
Array(
  'result' => Array (
        0 => Array(
            "id" => "111",
            "title" => "no title",
            "comments" => Array ( "id" => "1", "text" => "aaaa", "user" => Array("id" => "1"))
            ),
        "id" => "1"
      )
);

How to correctly compose a query on the doctrine in order to select only the required fields, while maintaining the nesting structure?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tashiro, 2013-12-10
@Tashiro

figured out
you need to use this syntax

->addSelect(array("partial u.{id,name}","c", "cu"))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question