Optimizing doctrine queries in Sonata Admin with LeftJoin

折月煮酒 提交于 2019-12-12 01:54:58

问题


How do you optimize the DB queries made by sonata admin in the list and edit views ?

i LeftJoined some queries that i made using the querybuilder in my entity repository , this already helped a lot, brought my queries down from 100+ to about 22.

But the remaining queries are the ones that happen automatically by using the formbuilder and listmapper.

Is there anyway i can further optimize the queries made by those classes ? im not even sure at this point where the queries are made... i tried to overwrite the findBy, findAll methods of the repository but they seem to use something like

$persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName);
return $persister->load($criteria, null, null, array(), 0, 1, $orderBy);

Not sure how i can add a join statement to that...

And i guess it's not just in the sonata admin but also for queries that i use in the front-end that use the built-in EntityRepository find, findAll, findOneBy etc... functions.


回答1:


In your admin class override the createQuery() method like this :

public function createQuery($context = 'list')
{
    $query = parent::createQuery($context);

    $query
        ->addSelect(...)
        ->leftJoin(...) // use $query->getRootAlias() here
    ;

    return $query;
}

For the edit view it's a little bit more tricky because you need to override the sonata controller by extending Sonata\AdminBundle\Controller\CRUDController and then override the editAction() method.

The controller name can be specified in the third argument of the service declaration.




回答2:


I know it some month but if it can help someone :

I didn't wanted to change the controller so i take a look inside the code.

In your admin class, you can override the function getObject($id):

// code from sonata admin class
public function getObject($id)
{
    $object = $this->getModelManager()->find($this->getClass(), $id);
    foreach ($this->getExtensions() as $extension) {
        $extension->alterObject($this, $object);
    }
    return $object;
}

Then put your own code in and return your object.

That's all, no need to override sonata controller.



来源:https://stackoverflow.com/questions/26447306/optimizing-doctrine-queries-in-sonata-admin-with-leftjoin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!