symfony - Doctrine partial queries return the complete object -
i'm trying optimize query need simple list entity affiliated several entities. created query, should give me id , name:
public function findallorderbyname() { $qb = $this->createquerybuilder('a'); $query = $qb->select(array('partial a.{id,name}')) ->addorderby('a.name', 'asc') ->getquery(); return $query->getresult(); }
return in controller this:
public function getinstrumentsaction() { $instruments = $this->getdoctrine()->getrepository('acmeinstrumentbundle:instrument')->findallorderbyname(); return array('instruments' => $instruments); }
rather give me 2 camps, gives me complete object, including fields of other related entities.
why did not work?
it worked designed. observing lazy loading of of related entities.
start adding:
echo $query->getsql() . "\n"; return $query->getresult();
you see like:
select p0_.id id0, p0_.name name1 instrument p0_ order p0_.name asc
so 2 fields asked being queried.
echo sprintf("instrument %s %s %s\n", $instrument->getname(),$instrument->getsomeotherscalervalue());
you see while name echoed, other value not though it's in instrument table.
as far relations go, let's suppose instrument has onetomany relation persons.
$persons = $instrument->getpersons();
you sort of expect $persons empty array it's rather smart doctrine\orm\persistentcollection. try else $person (even simple count($persons) query triggered , linked person objects loaded.
so seeing. can see queries in logs/dev.log. long pull in instrument 1 query generated. try relation, query goes out.
work arounds
don't try access relations.
before accessing relation $persons->setinitialized(true); prevent loading. bit of pain.
since optimization goal return array result. no objects @ all.
you can go ahead , join relations in query use partial bring in id of related entity. query works bit harder won't need worry additional queries getting triggered.
it kind of nice if there way prevent lazy loading on query specific basis. if there is, have not been able find it.
Comments
Post a Comment